簡體   English   中英

使用ScreenUtils將截圖保存為libgdx中的圖像

[英]using ScreenUtils to save screenshot as image in libgdx

我正在使用ScreenUtils.getFrameBufferPixels(...)來截取游戲畫面。 我想將此方法返回的字節數組保存為文件中的圖像。 我正在使用libGDX和我在android中的重點。

現在相當容易。 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;
    }
}

我很幸運,這里有一個libGDX論壇成員提供的最小.PNG編碼器: http//www.badlogicgames.com/forum/viewtopic.php? p = 8358#p8358

請注意,生成的PNG未經過優化,因為編碼器非常簡單(我使用pngcrush離線來顯着減小它們的大小)。

我也遇到了alpha通道的一些問題。 底層屏幕顏色通過屏幕上的透明像素顯示,但不會從屏幕上刮下的像素中出現(因此這不是PNG編碼器的錯誤)。 如果你的背景是黑色的,那么只需確保alpha通道的像素為1.0(除非你想要截圖中的透明度)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM