Rendering to an Image

From Slick2D Wiki
Jump to: navigation, search

Sometimes you might want to create graphics procedurally using code. This is where rendering to an image fits perfectly.

To render into an image you first need to create a new one and get access to its graphics context.

private Image localImg;
private Graphics localImgG;
try {
	localImg = new Image(256,256);
	localImgG = localImg.getGraphics();
} catch (SlickException e) {
	Log.error("creating local image or graphics context failed: " + e.getMessage());
}

The code fragment above creates an image of size 256 x 256 pixels and retrieves the graphics context of the image (localImgG).

Now we are prepared to draw on the image, so let's clear the image and prepare it with a background color of our choice:

localImgG.setBackground(new Color(0,0,0,0));
localImgG.clear();

Now let's draw something simple like a green rectangle onto the image:

localImgG.setColor(Color.green);
localImgG.drawRect(10, 10, 20, 20);

Once you finish drawing, you need to flush the operations to the actual context. You can then return the localImg for your game.

localImgG.flush();
...
g.drawImage(localImg, 100, 100);

But just a hint: on my machine it takes around a second to retrieve the GraphicsContext for an Image! This is of course not bearable in a game… To work around this I created a static Image and its appropriate GraphicsContext on game startup. Whenever I want to create a procedurally generated image I use the static one for all drawing commands. Finally I return a copy of the static image to be used in my game code. And this is fast enough. It works like this:

Image img = new Image(width, height);
localImgG.copyArea(img, 0, 0);
return img;