gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:59:19 24 4
gpt4 key购买 nike

嗨,我正在尝试使用 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);

关于java - 如何在java中创建图形对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28945390/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com