我使用 Graphics2D 绘制了三个箭头。
- 三个
drawLine
绘制(形状)
填充(形状)
这是放大后的样子:
我无法理解两件事:
- 为什么填充后的尺寸变小并且发生了偏移?
- 其次,为什么箭头 1. 和 3. 看起来不同?两者均由 3 条抗锯齿线组成。它们(可能)不应该仅在顶点上有所不同吗?
这是完整的代码:
import javax.swing.*;
import java.awt.*;
public class ShapeTest extends JPanel
{
public static void main(String [] args)
{
JFrame frame = new JFrame();
frame.setSize(new Dimension(220, 200));
frame.add(new ShapeTest());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
@Override
protected void paintComponent(Graphics graphics)
{
super.paintComponent(graphics);
Graphics2D graphics2D = (Graphics2D)graphics;
graphics.setColor(Color.white);
graphics.fillRect(0, 0, this.getWidth(), this.getHeight());
graphics2D.setColor(Color.black);
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.drawLine(100, 40, 103, 46);
graphics2D.drawLine(103, 46, 106, 40);
graphics2D.drawLine(100, 40, 106, 40);
graphics2D.fill(new Polygon(
new int[]{100, 103, 106},
new int[]{50, 56, 50},
3
));
graphics2D.draw(new Polygon(
new int[]{100, 103, 106},
new int[]{60, 66, 60},
3
));
}
}
最佳答案
看来我已经找到了问题的答案。我将它们发布给可能面临同样问题的其他人。
较小,因为,如 MadProgrammer在问题下面的评论中说,笔画是沿着边缘通过中间绘制的,因此 1px 笔划边缘将是形状边缘每侧 0.5px。
因四舍五入而发生偏移。当您使用浮点精度坐标绘制一条线时,可以在某些平台上以某种方式对其进行标准化。在 Windows 上,至少对于 Path2D.Float
和 Line2D.Float
来说,它将坐标舍入为整数。我想 fill(Shape)
也是如此。幸运的是,您可以通过以下方式禁用笔画标准化:
g2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
它解决了问题:
不同,因为渲染算法不同。
关于java - Graphics2D 线条和形状绘制问题(渲染在错误的位置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41900219/