Unable to draw thin lines using Java2D

I am trying to draw a polygon in 1 pixel increments. Since the whole polygon is scaled to 100, I set the line width to 0.01. For some reason, however, the polygon is drawn with a line width on the screen that looks like 100 pixels instead of 1.

I use GeneralPathas a polygon shape. Thin lines are drawn if I use the same approach for drawing shapes Line2D.

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

New information: If I delete the setStroke line, I get the 2-pixel line correctly, since BasicStroke 0.02f was previously installed on the Graphics2D object.

This is the real setStroke line

g.setStroke(new BasicStroke((float) (1f / getRoot().scaleX)));
+3
source share
3 answers

. . , 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

+3

, .

+1

This also sets the width to 1px for the lines:

graphics2D.setStroke(new BasicStroke(0));
0
source

Source: https://habr.com/ru/post/1748520/


All Articles