using ScreenUtils to save screenshot as image in libgdx(使用 ScreenUtils 将屏幕截图保存为 libgdx 中的图像)
问题描述
我正在使用 ScreenUtils.getFrameBufferPixels(...) 来截取游戏画面.我想将此方法返回的字节数组保存为文件中的图像.我正在使用 libGDX,我的重点是 android.
I am using ScreenUtils.getFrameBufferPixels(...) to take a screenshot of the game screen. I want to save the byte array returned by this method as an image in file. I am using libGDX and my focus in android.
推荐答案
现在相当容易.Libgdx 提供了一个示例.
It is now fairly easy. Libgdx provides an example.
我必须添加一条语句才能使其正常工作.图片无法直接保存到 /screenshot1.png.只需添加 Gdx.files.getLocalStoragePath().
I had to add one statement to get it working. The image could not be saved directly to /screenshot1.png. Simply prepend 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;
    }
}
                        这篇关于使用 ScreenUtils 将屏幕截图保存为 libgdx 中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 ScreenUtils 将屏幕截图保存为 libgdx 中的图像
				
        
 
            
        - 未找到/usr/local/lib 中的库 2022-01-01
 - 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
 - 如何指定 CORS 的响应标头? 2022-01-01
 - 转换 ldap 日期 2022-01-01
 - Eclipse 的最佳 XML 编辑器 2022-01-01
 - 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
 - java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
 - 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
 - GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
 - 获取数字的最后一位 2022-01-01
 
						
						
						
						
						
				
				
				
				