无法用Java2D绘制细线

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

以下代码生成下面的输出。 您的代码中的其他位置必须有错误。 也许您在问题中省略了另一个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); } } 

在此处输入图像描述

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

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

 graphics2D.setStroke(new BasicStroke(0));