LukTar LukTar - 4 months ago 48
Android Question

Libgdx - screenshot poor quality

I try to make a screenshot of my game according to this article:
https://github.com/libgdx/libgdx/wiki/Taking-a-Screenshot

It seams that there is problem with black color in PNG conversion.

My screenshots looks as follow:


  • should be:



enter image description here


  • is:



enter image description here

Here is detailed view:

enter image description here

There is a strange color instead of shadow around a leaf.

Did anyone have a similar problem?

Answer

I resolved this problem by implementing platform specific mechanism - it's different for android and desktop applications.

You can find more about platform specific code in libgdx here.

Here is the interface for android:

public interface ScreenshotPixmap {
    public void saveScreenshot(FileHandle fileHandle);
}

And implementation:

public class AndroidScreenshotPixmap implements ScreenshotPixmap {

public Pixmap getScreenshot( int x, int y, int w, int h, boolean flipY ) {

    Gdx.gl.glPixelStorei( GL20.GL_PACK_ALIGNMENT, 1 );

    final Pixmap pixmap = new Pixmap( w, h, Pixmap.Format.RGBA8888 );
    ByteBuffer pixels = pixmap.getPixels();
    Gdx.gl.glReadPixels( x, y, w, h, GL20.GL_RGBA, GL20.GL_UNSIGNED_BYTE, pixels );

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

    return pixmap;
}

public int[] pixmapToIntArray( Pixmap pixmap ) {
    int w = pixmap.getWidth();
    int h = pixmap.getHeight();

    int dest = 0;
    int[] raw = new int[w * h];
    for ( int y = 0; y < h; y++ ) {
        for ( int x = 0; x < w; x++ ) {
            int rgba = pixmap.getPixel( x, y );
            raw[dest++] = 0xFF000000 | ( rgba >> 8 );
        }
    }
    return raw;
}

public void savePNG( int[] colors, int width, int height, OutputStream stream ) {
    Bitmap bitmap = Bitmap.createBitmap( colors, width, height, Bitmap.Config.ARGB_8888 );
    bitmap.compress( Bitmap.CompressFormat.PNG, 100, stream );
}

@Override
public void saveScreenshot(FileHandle fileHandle) {
    Pixmap pixmap = getScreenshot(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
    OutputStream stream = fileHandle.write(false);
    savePNG(pixmapToIntArray(pixmap), Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), stream);
}
}

Good luck.