Sunday, June 22, 2014

[libgdx] day 19 – pixmaps

A Pixmap contains image data in your main memory. You can change the data of the pixmap and then create a texture of it that you can use.
You can either create a pixmap from an existing file or by defining its size.
Pixmap pixmap = new Pixmap( 32, 32, Format.RGBA8888 );

Pixmap pixmap = new Pixmap(Gdx.files.internal("graphics/test.png"));
There are some methods to draw on pixmaps. (more in the API as allways :P)
pixmap.setColor( 0, 1, 0, 1);
pixmap.fillCircle( 16,16,16 );
pixmap.setColor( 1, 0, 0, 1);
pixmap.drawRectangle( 5,5, 10,10);
After you created a Texture from the Pixmap you probably will not need it anymore. So dispose it right now.

Texture texture = new Texture( pixmap );
pixmap.dispose();
You as well can save the Pixmap to a png-file:
PixmapIO.writePNG(Gdx.files.local("cache/test.png"), pixmap);
pixmap.dispose();
You can use these pixmaps to save a screenshot:
public static void saveScreenshot(FileHandle pFile, int pX, int pY, int pWidth, int pHeight){
    Pixmap pixmap = getScreenshot(pX, pY, pWidth, pHeight, true);

    PixmapIO.writePNG(pFile, pixmap);
    pixmap.dispose();
}

public static Pixmap getScreenshot(int pX, int pY, int pWidth, int pHeight, boolean pFlipY) {
    Gdx.gl.glPixelStorei(GL10.GL_PACK_ALIGNMENT, 1);

    Pixmap pixmap = new Pixmap(pWidth, pHeight, Format.RGBA8888);
    ByteBuffer pixels = pixmap.getPixels();
    Gdx.gl.glReadPixels(pX, pY, pWidth, pHeight, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, pixels);

    final int numBytes = pWidth * pHeight * 4;
    byte[] lines = new byte[numBytes];
    if (pFlipY) {
            final int numBytesPerLine = pWidth * 4;
            for (int i = 0; i < pHeight; i++) {
                    pixels.position((pHeight - i - 1) * numBytesPerLine);
                    pixels.get(lines, i * numBytesPerLine, numBytesPerLine);
            }
            pixels.clear();
            pixels.put(lines);
    } else {
            pixels.clear();
            pixels.get(lines);
    }

    return pixmap;
}
(code from http://code.google.com/p/libgdx-users/wiki/Screenshots)
test screenshot
I finally managed to get collisions with the tilemap in an acceptable way (if your player is smaller than the tiles). I hopefully will create this tutorial for tomorrow.

No comments:

Post a Comment

Popular Posts