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)));
4

3 回答 3

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);
    }
}

在此处输入图像描述

于 2010-06-04T12:51:01.283 回答
0

这也为线条设置了 1px 宽度:

graphics2D.setStroke(new BasicStroke(0));
于 2012-02-18T18:46:39.317 回答
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
于 2021-03-21T00:26:09.857 回答