Reputation: 35276
I created an ARGB BufferedImage. Now I'd like to reinitialize it with a transparent background. I tried the following code:
(...)
if( this.offscreen==null ||
this.offscreen.getWidth()!= dim.width ||
this.offscreen.getHeight()!= dim.height )
{
this.offscreen=new BufferedImage(
dim.width,
dim.height,
BufferedImage.TYPE_INT_ARGB);
}
Graphics2D g=this.offscreen.createGraphics();
g.setColor(new Color(255,255,255,0));
g.clearRect(0, 0, dim.width, dim.height);
(...)
but it didn't work.
Any idea on how to do this please ?
Thanks !
Upvotes: 2
Views: 8078
Reputation: 124
I had this problem before and I solved it with a really narrow trick. Here is the deal:
In the constructor of the paint Class take a screen shot of the System but be careful
BufferedImage image = new Robot().createScreenCapture(new Rectangle(0, 23, xScreen, yScreen));
And where you want to clear the screen
g2D.drawImage(image, null, /*your Image observer*/);
Upvotes: -1
Reputation: 22721
g.clearRect(..)
fills the selected rectangle with the background colour of the Graphics2D
object. You're better off doing g.fillRect(..)
which would give the intended result with your code, or set the background colour of the Graphics2D
object beforehand (g.setBackground(..)
).
Also, you may have to do g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC));
before the fill so that it sets the buffer properly (ignore destination buffer data, only use source data -- in this case, the fill operation). Not sure what the default is for this value, but you should set it back to that afterwards to ensure proper operation.
Upvotes: 2