【问题标题】:using ScreenUtils to save screenshot as image in libgdx使用 ScreenUtils 将屏幕截图保存为 libgdx 中的图像
【发布时间】:2012-09-28 17:33:59
【问题描述】:

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

【问题讨论】:

    标签: java android libgdx


    【解决方案1】:

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

    我必须添加一条语句才能使其正常工作。图片无法直接保存到/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;
        }
    }
    

    【讨论】:

      【解决方案2】:

      我很幸运使用 libGDX 论坛成员提供的最小 .PNG 编码器:http://www.badlogicgames.com/forum/viewtopic.php?p=8358#p8358

      请注意,生成的 PNG 没有经过优化,因为编码器非常简单(我离线使用 pngcrush 来显着减小它们的大小)。

      Alpha 通道也有一些问题。底层屏幕颜色通过屏幕上的透明像素显示,但不会通过从屏幕上刮下的像素显示(因此这不是 PNG 编码器的真正故障)。如果您的背景是黑色的,那么只需确保 Alpha 通道的像素为 1.0(当然,除非您想要屏幕截图中的透明度)。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-13
      • 2014-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-05
      • 2015-05-19
      • 2019-09-16
      相关资源
      最近更新 更多