-->

有什么办法来绘制在Swing亚像素精度的线?(Is there any way to draw li

2019-06-28 09:24发布

这个问题已经被问过 ,但答案不解决这个问题,所以我再问一下。

有人建议,而不是使用g2.drawLine ,你可以使用g2.draw(line) ,其中line是一个Line2D.Double 。 然而,如可以从截图看到,线依然绘制,就好像它们在整数像素结束(每组10条线是完全平行)。

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Line2D;

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);
    // Base case, with ints, looks exactly the same:
    //              g2.drawLine(5, (int)y, 200, (int)(y + delta));
                }
            }
        });

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

因此,它是不可能在Swing正确渲染不完全结束在像素上线?

Answer 1:

尝试设置如下:

g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); 

从这个答案摘自: 爪哇-是否子像素线条精确度要求的AffineTransform?

下面是比较结果:



文章来源: Is there any way to draw lines with subpixel precision in Swing?