如何在 java 中创建图形对象?

how can I create a graphics object in java?

您好,我正在尝试使用 java

生成图像
int width = 640; int height= 480;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics g2 =  image.getGraphics();
    g2.setColor(Color.BLUE);
    g2.clearRect(0, 0, width, height);
    ImageIO.write(image, "PNG", new File(path+index+".png"));

我期待一张蓝色的图片...但它是黑色的。 你知道为什么吗?

它是黑色而不是蓝色,因为 clearRect 使用 背景色 填充矩形,这不是您使用 setColor 设置的颜色。

clearRect 的 API 文档说:

Clears the specified rectangle by filling it with the background color of the current drawing surface. This operation does not use the current paint mode.

Beginning with Java 1.1, the background color of offscreen images may be system dependent. Applications should use setColor followed by fillRect to ensure that an offscreen image is cleared to a specific color.

因此,使用 fillRect 而不是 clearRect

g2.setColor(Color.BLUE);
g2.fillRect(0, 0, width, height);

Graphics::clearRect() 使用当前颜色(或者更确切地说:Paint)。

Javadoc:

Clears the specified rectangle by filling it with the background color of the current drawing surface. This operation does not use the current paint mode.

解决方案:改用fillRect()