applemavs
applemavs

Reputation: 503

Change alpha of image in java for method drawImage()

I'm trying to change the transparency of an image over time, and I'm doing this with the method drawImage() from java.awt.Graphics. I know there's a lot of different answers online about how to do this, but I can't find a one that is simple enough for me to understand and implement.

Let's just say I have a BufferedImage image, and I want to draw this image with a 50% opacity. How would I initialize image and what would I do to adjust the alpha level of the image when I draw it. It would be great if I could use the method drawImage() and do something with that to change the transparency of the image, but it's probably not that simple.

Upvotes: 2

Views: 10819

Answers (2)

Stalin Gino
Stalin Gino

Reputation: 622

Using image filter.

float[] scales = { 1f, 1f, 1f, 0.1f };
float[] offsets = new float[4];
RescaleOp rop = new RescaleOp(scales, offsets, null);
g2d.drawImage(buffimg, rop, 0, 0);

4th element in scales array is transparency, this value goes between 0 - 1

Answer by camickr will make the entire component apply the alpha including all inner components. But that will be much faster.

Warning: Use Image Filters with Care

ref: http://www.informit.com/articles/article.aspx?p=1013851&seqNum=2

Upvotes: 1

camickr
camickr

Reputation: 324207

Never tried it, but I think the basic code would be:

AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
g2d.setComposite(ac);
g2d.drawImage(...);

Upvotes: 9

Related Questions