views:

47

answers:

1

Could someone provide an example of how to dynamically create an image in Java, draw lines et cetera on it, and then draw the image so that areas not painted will remain transparent in the drawing process?

+4  A: 

One could use a BufferedImage with an image type that supports transparency such as BufferedImage.TYPE_INT_ARGB:

BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);

One can draw on the BufferedImage by calling BufferedImage.createGraphics to obtain a Graphics2D object, then perform some drawing:

BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);

Graphics2D g = img.createGraphics();
g.drawLine(0, 0, 10, 10);  // draw a line.
g.dispose(); 

Then, since BufferedImage is a subclass of Image that can be used to draw onto another Image using one of the Graphics.drawImage that accepts an Image.

coobird
Thank you so much! It was very frustrating when a normal image object was not doing the job. My roommate looked at me weirdly after the much rejoicing from seeing it work correctly. :-)
Noctis Skytower
You're welcome :) Glad things worked out!
coobird