Keilly: September 2007

Thursday, September 27, 2007

Clear a BufferedImage in Java

Lots of cool Animations require a transparent background and, of course, speed.

In Java creating a new BufferedImage for each frame of an animation is slow, but reusing images with transparency from frame to frame is tricky as BufferedImage doesn't have an obvious way to set all of it's pixels to completely transparent.

Unlike other colors we can't just paint a transparent color over the image because, well, it's transparent and won't affect the pixels already in the image.

I had a poke around and found this from IBM DeveloperWorks.

g2D.setComposite(
AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
Rectangle2D.Double rect =
new Rectangle2D.Double(0,0,width,height);
g2D.fill(rect);

It would be a lot more useful if clearing to any color was part of the Image API, but until then this is good to know.