Pixmaps, as the name implies is a map of pixels, each pixel containing a level for red, green and blue and sometimes alpha. They can be used to store image data and can be generated on the fly in your application. Pixmaps reside in native heap memory and should be disposed when they are no longer needed. Pixmaps can be created in libgdx using a variety of formats such as RGBA8888, RGBA4444, RGB888 and RGB565. These formats simply tell the pixmap how to store the colour and alpha values. RGBA8888 for example stores each value, R,G,B and alpha as 8-bit values, 000000FF as black and FFFFFFFF as white.
Why use pixmaps instead of saved images?
Well, if you have a single image with lots of variation such as a ball that is sometimes drawn with spikes, sometimes with a glow, sometimes with an aura etc. Then you can use pixmaps to combine these images into a single texture at runtime. Another example would be a character creation screen, here we use lots of separate images together to create a character. A pixmap could be used here to store the finished character. Another reason is loading an image from a disk is a lot slower than creating the image on the fly, so there’s a speed improvement when using pixmaps. This, however, isn’t much of an issue if you’re using an asset manager. (which I highly suggest you do)
How to use a pixmap
First we create a pixmap with a width of 16, a height of 16, and format of RGBA8888.
1 |
Pixmap pmap = new Pixmap(16,16,Format.RGBA8888); |
Then we can start drawing our pixels to it. Here we will fill the pixmap with white and draw a small red circle in the center.
1 2 3 4 5 |
pmap.setColor(Color.WHITE); pmap.fill(); pmap.setColor(Color.RED); pmap.fillCircle(8, 8, 4); |
Now we add 4 dark blue pixels, one in each corner.
1 2 3 4 5 |
pmap.setColor(new Color(0,0,.5f,1)); pmap.drawPixel(0, 0); pmap.drawPixel(15, 0); pmap.drawPixel(0, 15); pmap.drawPixel(15, 15); |
You should now have an image like this
Now let’s make another pixmap this time 32 x 32.
1 |
Pixmap pmapl = new Pixmap(32,32, Format.RGBA8888); |
And draw our smaller pixmap to it 3 times twice normally and once stretched on the right.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
pmapl.drawPixmap(pmap, 0, 0); pmapl.drawPixmap(pmap, // the image 0, // the x location to start drawing 16); // the y location to start drawing pmapl.drawPixmap(pmap, //the image 0, // the source x start position 0, // the source y start position 16, // the width of the source to be taken 16, // the height of the source to be taken 16, // the x location to start drawing the image in the pixmap 0, // the y location to start drawing the image in the pixmap 16, // the width to draw our image 32); // the height to draw our image |
You should now have an image like this
Now you can create a new texture with the image and dispose your no longer required pixmaps.
1 2 3 |
texture = new Texture(pmapl); pmap.dispose(); pmapl.dispose(); |
Further Reading: