无法使用Java2D绘制细线

5
我正在尝试用1像素的线条绘制多边形。由于整个多边形被放大了100倍,因此我将线宽设置为0.01。但是由于某种原因,多边形的屏幕线宽看起来似乎是100像素而不是1像素。
我使用GeneralPath作为多边形的形状。如果我使用相同的方法绘制Line2D形状,则会绘制出细线。
g2d.scale(100, 100);
g2d.setStroke(new BasicStroke(0.01f));
g2d.draw(theShape);

新信息:如果我删除setStroke行,则可以正确地获得2像素线,因为之前在Graphics2D对象上设置了0.02f的BasicStroke。

这是真正的setStroke行。

g.setStroke(new BasicStroke((float) (1f / getRoot().scaleX)));

请确认一下 getRoot().scaleX 打印的值是多少? - aioobe
  1. 我已经通过打印传递给BasicStoke的参数以及getLineWidth返回的内容来检查它是0.01f。
- Bart van Heukelom
2个回答

5
以下代码产生了下面展示的输出结果。你的代码中必定存在其他错误。也许是你在提问中省略了另一个对于scale的调用:
import java.awt.*;

public class FrameTest {
    public static void main(String[] args) throws InterruptedException {

        JFrame f = new JFrame("Demo");
        f.getContentPane().setLayout(new BorderLayout());    
        f.add(new JComponent() {
            public void paintComponent(Graphics g) { 
                Graphics2D g2d = (Graphics2D) g;

                GeneralPath theShape = new GeneralPath();
                theShape.moveTo(0, 0);
                theShape.lineTo(2, 1);
                theShape.lineTo(1, 0);
                theShape.closePath();

                g2d.scale(100, 100);
                g2d.setStroke(new BasicStroke(0.01f));
                g2d.draw(theShape);
            }
        });

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(300, 300);
        f.setVisible(true);
    }
}

enter image description here


很奇怪。我不认为有遗忘的比例尺。形状的大小没问题,只是笔画太宽了。 - Bart van Heukelom
你是否在正确的图形对象上设置了描边?能否发布更多代码? - aioobe
是的,我正在正确的对象上进行设置。无论如何,问题中添加了新信息。如果这不起作用,我会发布更多内容。 - Bart van Heukelom
我改了点什么,不知道是什么,但现在它可以工作了。如果我能再次重现这个错误,我会在这里告诉你的。接受这个答案是因为你仍然付出了很大的努力来帮助。 - Bart van Heukelom

0

关于零宽度描边是否应该绘制发际线还是什么都不绘制,似乎存在一些争议:https://bugs.openjdk.java.net/browse/JDK-8111947

我在这方面运气很好。在所有转换完成后调用。

// Make a 2 pixel wide stroke
Stroke stroke = new BasicStroke(2/(float)Math.min(Math.abs(g2d.getTransform().getScaleX()),
                                                  Math.abs(g2d.getTransform().getScaleY())));
g2d.setStroke(stroke);
g2d.draw(shapeForDrawing); // convert center to upper left corner as required by Ellipse2D.Double

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接