开发者

Java Draw Line based on doubles (sub-pixel precision)

开发者 https://www.devze.com 2023-04-13 09:13 出处:网络
I am making a basic Java program and I would lik开发者_StackOverflow中文版e to draw a line using basic swing Graphics.drawLine.

I am making a basic Java program and I would lik开发者_StackOverflow中文版e to draw a line using basic swing Graphics.drawLine.

Is there a way to make the two points in terms of doubles so I can make the output more accurate, or another way that is better?


You can draw the lines using ((Graphics2D) g).draw(Shape) and pass it a Line2D.Double.

Here's a demo:

Java Draw Line based on doubles (sub-pixel precision)

import javax.swing.*;

public class FrameTestBase extends JFrame {

    public static void main(String args[]) {
        FrameTestBase t = new FrameTestBase();
        t.add(new JComponent() {
            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                    RenderingHints.VALUE_ANTIALIAS_ON);
                for (int i = 0; i < 50; i++) {
                    double delta = i / 10.0;
                    double y = 5 + 5*i;
                    Shape l = new Line2D.Double(5, y, 200, y + delta);
                    g2.draw(l);
                }
            }
        });

        t.setDefaultCloseOperation(EXIT_ON_CLOSE);
        t.setSize(400, 400);
        t.setVisible(true);
    }
}

You might also want to try adding

g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
                    RenderingHints.VALUE_STROKE_PURE)


If you have a refernce to g, which I assume is Graphics object, you should use Java 2D APIs

Graphics2D g2 = (Graphics2D) g;
g2.draw(new Line2D.Double(x1, y1, x2, y2));

Javadocs for:

  • Line2D
  • Graphics2D
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号