Hi I'm trying to generate an image with 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"));
I'm expecting a blue image... but it's black. Do you know why?
It's black instead of blue because clearRect
fills the rectangle with the background color , which is not the color that you set with setColor
.
The API documentation of clearRect
says:
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 byfillRect
to ensure that an offscreen image is cleared to a specific color.
So, use fillRect
instead of clearRect
.
g2.setColor(Color.BLUE);
g2.fillRect(0, 0, width, height);
Graphics::clearRect()
does not use the current Color (or rather: 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.
Solution: use fillRect()
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.