I’m writing a simple 2D game in Java, and I was wondering how to display a bufferedImage with a transparent color key.
You can either use png or gif. Both offer bitmask transparency (and png also supports a full alpha channel).
Just load the image and copy it over in order to get a managed image (pre 1.5 requires that).
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
GraphicsConfiguration gc = device.getDefaultConfiguration();
[...]
accelImage = gc.createCompatibleImage(32,32,Transparency.BITMASK);
Graphics2D tg = (Graphics2D)accelImage.getGraphics();
tg.setComposite(AlphaComposite.Src);
tg.drawImage(loadedImage,0,0,null);
tg.dispose();
You can also create the bitmask with a specific color (color key) but that’s more work. However, a loader wich handles that is floating around here somewere.
Well, using the format’s bitmask stuff is usually nicer to do then drawing everything with an ugly background color. Just use 4 or 8bit pngs or gifs.
If you don’t have a programm to create those images try Gimp. It’s free
For the smallest possible png size you can use pngout by Ken Silverman:
http://advsys.net/ken/utils.htm
(Yes. That’s a bit more than you’ve asked for - but waiting for pizza is really tough ;))
How would you set the bitmask to make a specific color transparent? And would this only work with 8 bit .PNG files? Also, I’ve gotten the default built-in transparency to work with .GIF files, but .PNG doesn’t seem to work regardless of the bps I set it to. I’ve tried using both IrfanView and the PNGOUT.exe