Java 2D - Copying an image while retaining transparency

Hi,

I looked about on similar posts but couldn't find anything that related exactly to this problem, sorry if it's a repeat.

I'm attempting to paint some smaller images onto a background and want them to be transparent and rotate around. I've loaded the images into an arrayobjectImages and if I draw them straight on, then the transparency works fine. However, I also want to rotate the images before drawing them on, but this causes them to lose their transparency and I can't seem to fix it.

Here's the relevant code. I've not included it all because it's rather large, but pv is the JPanel they're being drawn onto and current is just an object being used to store the data on the object the image represents.

g.drawImage(background, 0, 0, pv);

...

// Retreive the relevant image

Image img = objectImages[current.getImageID()];

// Get the orienation of the image

double angle = current.getOrientation();

// Make a blank image to draw the copy onto

int length = Math.max(img.getWidth(pv), img.getHeight(pv));

Image imgCopy = pv.createImage(length, length);

Graphics2D g2 = (Graphics2D) imgCopy.getGraphics();

// Rotate around the center

AffineTransform affT =new AffineTransform();

affT.rotate(angle, length/2, length/2);

// Draw the rotated image onto the empty image's graphics

g2.drawImage(img, affT, pv);

g2.dispose();

// Find out where this image is so we know where to draw it

Point loc = current.getLocation();

// Draw it on

g.drawImage(imgCopy, loc.x, loc.y, pv);// Changing imgCopy here to img fixes the transparency, but obviously breaks the rotation.

[2146 byte] By [St00a] at [2007-11-26 23:06:56]
# 1

The problem is that the intermediate image that you're creating

(imgCopy) is opaque, so you lose transparency of the original

image when you render to it.

If you change the code to something like this:

Image imgCopy = pv.getGraphicsConfiguration().createCompatibleImage(length, length, Transparency.TRANSLUCENT);

it should work. (if your images are transparent and not translucent,

you can use BITMASK instead of TRANSLUCENT)

However, I don't quite understand why do you need to render to

the intermediate image to do the transformation.

You can just as easily render the original images transformed,

you'll just need to tweak the affine transform's parameters a bit

to rotate the image around your "current.getLocation()" point, that's all.

So, you can do something like this:

Graphics2D g2d = (Graphics2D)g.create(); // create a clone of graphics so that you don't mess up the transform of the original context

g2d.rotate(angle, loc.x, loc.y); // or whatever - you need to tweak x,y a bit

g2d.drawImage(img, 0, 0, null);

g2d.dispose();

Thanks,

Dmitri

Java2D Team

dmitri_trembovetskia at 2007-7-10 14:00:53 > top of Java-index,Security,Cryptography...
# 2
Thank you Dmitri, that worked perfectly!
St00a at 2007-7-10 14:00:53 > top of Java-index,Security,Cryptography...