how do i draw a normal image at 50% alpha

i had a look thru the API’s and searched on this forum, coultn’t find an answer, so i’ll ask.

how do i draw a square image eg:

getClass().getResource("images/SPiece.gif")

which has no alpha or transparency, at something like 50% transparency (to give it a ghost effect).

it’s not necessary to get high performance from it.

what i’m using now is the usual g.drawImage(img, x, y, null).

using PNG works, but it means having to have 2 image files with the game, and then the alpha level can’t be altered for things like fading…

You need to cast your Graphics instance into a java.awt.Graphics2D. Then you can set the composite to a java.awt.AlphaComposite:


Graphics2D g = (Graphics) g1d;

g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC,0.5f));
g.drawImage(image,0,0,null);

Just typed this code, so it may not be dead on. Also you might want to play with SRC to get the effect you want.

Kev

didnt seem to be doing anything…

getInstance(int rule, float alpha)
Creates an AlphaComposite object with the specified rule and the constant alpha to multiply with the alpha of the source.

does that mean that if my image has zero alpha it will always be zero?

anyway i’ll have another look and fiddle with it.

edit: it even makes my 25% transparent png’s that i made up as a workaround totally opaque.

thanks. read the diferent rules and tried a couple of them out… tried XOR and the image disappeared. SRC_OVER did what i wanted. it says this:

public static final int SRC_OVERPorter-Duff Source Over Destination rule. The source is composited over the destination.

thanks for your help. the api is really hard to find stuff in when you don’t know exactly what it is you should be looking for

render(Graphics g)
{
Graphics2D g2d = (Graphics2D)g
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
g2d.drawImage((piece[i][j]).image, x+(i24), y+(j24), owner.mainFrame);
}

Great, thanks for providing the correct version aswell :slight_smile:

Kev

thanks. here’s it in action in my game, source included.

http://www.adam.com.au/kellyjones/java/

just download the JAR file and run it however you usually do. if you want the music grab the midi zip as well, or use your own midi files in a midi subdirectory in the same place the JAR is run from.

the code is used in the Tetroid object’s renderGhost() method. let me know what you think