使用ScreenUtils将截图保存为libgdx中的图像

Ram*_*miz 5 java android libgdx

ScreenUtils.getFrameBufferPixels(...)用来拍摄游戏画面的截图.我想将此方法返回的字节数组保存为文件中的图像.我正在使用libGDX和我在android中的重点.

Nik*_*las 4

现在相当容易。Libgdx 提供了一个示例

我必须添加一条语句才能使其正常工作。图像无法直接保存到/screenshot1.png. 只需预先添加Gdx.files.getLocalStoragePath().

源代码:

public class ScreenshotFactory {

    private static int counter = 1;
    public static void saveScreenshot(){
        try{
            FileHandle fh;
            do{
                fh = new FileHandle(Gdx.files.getLocalStoragePath() + "screenshot" + counter++ + ".png");
            }while (fh.exists());
            Pixmap pixmap = getScreenshot(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
            PixmapIO.writePNG(fh, pixmap);
            pixmap.dispose();
        }catch (Exception e){           
        }
    }

    private static Pixmap getScreenshot(int x, int y, int w, int h, boolean yDown){
        final Pixmap pixmap = ScreenUtils.getFrameBufferPixmap(x, y, w, h);

        if (yDown) {
            // Flip the pixmap upside down
            ByteBuffer pixels = pixmap.getPixels();
            int numBytes = w * h * 4;
            byte[] lines = new byte[numBytes];
            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);
        }

        return pixmap;
    }
}
Run Code Online (Sandbox Code Playgroud)