无法用Java2D绘制细线

时间:2010-06-04 12:41:25

标签: java java-2d

我正在尝试绘制一个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)));

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

我不知道为什么,但它现在有效。

答案 2 :(得分:0)

这也为行设置了1px宽度:

graphics2D.setStroke(new BasicStroke(0));

答案 3 :(得分: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