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.
18 comments:
this is exactly what i needed to solve my problem. thank you.
great, exactly what i was searching for. i love you!
11/10 for a great tip ! That's saved me a huge amount of time and angst. Thankyou
Thank you. You have saved me a lot of time by sharing that information.
thank you, very very usefully
Wow. My search has finally ended! :D
Very good, but you can also
clear an image with following code:
yourBufferedImage.createGraphics ().clearRect (0, 0, width, height);
To the previous poster: The javadoc for Graphics.clearRect(...) says it fills a rectangle with the current background color. This sounds quite different to really clearing an image.
How would you do this to only a section of your image and not the entire image?
Just set the rect to the area you want to clear.
I am unable to paint new shapes after i have cleared part or all of my BufferedImage.
Most likely because the composite is still set to be clearing shapes rather than filling in.
Try setting the composite back to something normal - easiest way to do this is just to create a new Graphics2D from the image and paint on that
Thanks. Really appreciate your article. I was stuck on this for many days.
Also, in my case I had to redraw the image and some new shapes. For this I did the following
Graphics2D newgraphics = panel1.getGraphics();
Composite backup=newgraphics.getComposite();
//set the composite to clear as per the Keilly's code
newgraphics.setComposite(...)
...
...
//Fill the cleared area with rectangle and then
newgraphics.setComposite(backup);
//and then re-load the image from a file and draw it ->
reloadimage();
newgraphics.drawImage(...)
panel1.updateUI();
Thanks, Keilly once again for sharing the article
Great post. Helped a lot. Thanks.
Dude, thanks a bunch.
Thanks. Brilliant tip.
hi, what type is the bufferedImage? When i use "TYPE_INT_ARGB", it doesn't work, but when i use "TYPE_INT_BGR", it works. Why?
Thank you so much. I spent a lot of days to solve my trouble with repainting on transparent background. Thank you very, very, very much!!!!
Post a Comment