我一直在开发一个简单的绘画程序,最近在我的绘画组件中重绘形状时遇到了障碍。
@Override
public void paintComponent(final Graphics theGraphics) {
super.paintComponent(theGraphics);
final Graphics2D g2d = (Graphics2D) theGraphics;
if (!preDrawnShapes.isEmpty() && !preDrawnShapeThickness.isEmpty()) {
for (int i = 0; i < preDrawnShapes.size(); i++) {
g2d.setStroke(new BasicStroke(preDrawnShapeThickness.get(i)));
g2d.draw(preDrawnShapes.get(i));
}
}
g2d.setStroke(new BasicStroke(currentThickness));
if (myShape != null) {
g2d.draw(myShape);
preDrawnShapeThickness.add(currentThickness);
}
}
这个paintComponent应该首先重绘之前绘制的形状,然后再绘制根据用户输入创建的新形状。
由于某种原因,绘制新形状时的形状厚度设置为当前厚度,但我之前绘制的任何形状的默认厚度均为 1。
preDrawnShapes 是一个 Shapes ArrayList,preDrawnShapeThickiness 是一个 Float Arraylist。
我在这里遗漏了什么吗?
更新:我发现 PreDrawnShapeThickness 只存储零的 float 。我不确定为什么。
最佳答案
增量绘画有两种常见的方法:
保留要绘制的对象的列表。然后,paintComponent() 方法迭代列表并绘制每个对象。因此,在您的情况下,自定义对象将包含您要绘制的形状以及形状厚度的 int 值。
只需将每个对象直接绘制到 BufferedImage 上即可。然后,您可以使用 JLabel 将 BufferedImage 显示为图标,或者进行自定义绘制来绘制 BufferedImage。
查看Custom Painting Approaches了解两种方法的示例。
关于java - 在paintComponent中重绘形状时无法保存描边/线条粗细,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33837623/