有没有办法在Swing中以亚像素精度绘制线条?

时间:2012-09-13 22:24:27

标签: java swing line subpixel

This question has been asked before,但答案并没有解决问题,所以我再问一遍。

有人建议您不要使用g2.drawLine,而是使用g2.draw(line),其中lineLine2D.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);
    }
}

non-parallel lines

因此,Swing无法正确渲染不完全在像素上结束的线条吗?

1 个答案:

答案 0 :(得分:6)

尝试设置以下内容:

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

取自这个答案: Java - Does subpixel line accuracy require an AffineTransform?

以下是比较结果:

enter image description here