java 基于双精度的Java Draw Line(亚像素精度)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7759549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:18:38  来源:igfitidea点击:

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

javaswing

提问by Adrian D'Urso

I am making a basic Java program and I would like to draw a line using basic swing Graphics.drawLine.

我正在制作一个基本的 Java 程序,我想使用基本的 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?

有没有办法在双打方面获得这两分,以便我可以使输出更准确,或者另一种更好的方法?

回答by aioobe

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

您可以使用绘制线条((Graphics2D) g).draw(Shape)并将其传递给Line2D.Double.

Here's a demo:

这是一个演示:

enter image description here

在此处输入图片说明

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)

回答by ring bearer

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

如果你有一个引用g,我假设它是Graphics对象,你应该使用 Java 2D APIs

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

Javadocs for:

Javadocs: