【问题标题】:BasicStroke causes offcenterBasicStroke 导致偏心
【发布时间】:2013-03-18 06:50:11
【问题描述】:

将 Graphics2D 对象的 BasicStroke 更改为 1 以外的任何值会导致它在启动时不在 JPanel 的中心绘制任何东西。

这是一个 JFrame 上的 JPanel。这是我项目的基本思想,但不是全部。

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    if(this.centered){
        this.myShape.setCenterX(this.getWidth()/2);
        this.myShape.setCenterY(this.getHeight()/2);
    }
    g2.setStroke(new BasicStroke(3)); //new BasicStroke(1) works fine
    g2.draw(this.myShape);
}

当您单击并拖动 myShape 时,myShape 将立即跳到中心。但是当我最初编译并运行它时,如果笔画不是 1,paintComponent() 会在屏幕中心上方约一厘米处绘制它。

我的居中方式有问题吗?我定义了 MyShape 类,所以那里可能有错误。也许中心和绘图点之间的距离是JPanel和JFrame顶部之间的空间?我该如何解决?

编辑:添加图片

http://s21.postimage.org/dfpmz73et/Untitled_1.png 第一个形状就在我想要的地方。另外两个在我想要的地方。但无论笔划大小如何,从中心的位移似乎都是相同的。

【问题讨论】:

  • 若想尽快获得更好的帮助,请附上sscce

标签: java swing graphics2d


【解决方案1】:

是的,我相信这是形状的正常行为。它假定轮廓为 1 个像素。因此,当您知道要更改基本笔划大小时,您需要更改中心计算。比如:

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    BasicStroke stroke = new BasicStroke(3);
    int adjustment = stroke.getLineWidth() - 1;

    if(this.centered){
        this.myShape.setCenterX(this.getWidth() + adjustment / 2);
        this.myShape.setCenterY(this.getHeight() + adjustment / 2);
    }
    g2.setStroke(stroke);
    g2.draw(this.myShape);
}

【讨论】:

  • 感谢您的回复。间距似乎与笔画大小无关(1除外),而且比几个像素大得多。不管我决定把我的形状放在哪里,它总是比正确的坐标高几个空格。我有一张图片来解释我的困境。
  • 图片没有帮助。正如 mre 已经建议的那样,SSCCE 确实如此。
猜你喜欢
  • 2019-04-04
  • 2015-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-21
  • 1970-01-01
  • 2013-03-03
  • 1970-01-01
相关资源
最近更新 更多