在libgdx中如何进行屏幕截图

4

我有一个应用程序,想要在游戏屏幕上截取屏幕截图并保存为图片上传到Facebook。我正在使用Libgdx,并且我的重点是android。

有谁能帮我以编程方式截取游戏屏幕截图并将其保存为图像?

5个回答

5

现在很容易做到。Libgdx提供了一个示例,可以在Taking a Screenshot页面上找到。

我需要添加一条语句才能使它工作。图像不能直接保存到 /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

简单解决方案:

Image screenShot = new Image(ScreenUtils.getFrameBufferTexture());

2
我只是想在这里添加一些内容。
当截屏时,我们需要考虑黑边和调整大小的窗口。如果您没有视口(适用于移动设备),请将装订线尺寸替换为0。
以下是如何正确地拍摄全屏截图:
final Pixmap pixmap = ScreenUtils.getFrameBufferPixmap(
                    MyGdxGame.viewport.getLeftGutterWidth(),
                    MyGdxGame.viewport.getTopGutterHeight(),
                    Gdx.graphics.getWidth() - MyGdxGame.viewport.getLeftGutterWidth() - MyGdxGame.viewport.getRightGutterWidth(),
                    Gdx.graphics.getHeight() - MyGdxGame.viewport.getTopGutterHeight() - MyGdxGame.viewport.getBottomGutterHeight());

然后,您可以使用PixmapIO保存一个像素图。https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/graphics/PixmapIO.html 注意:请注意y轴不是底部边距而是顶部边距。这是由于坐标系的差异造成的。这也是为什么图像颠倒的原因。
此外,您可以使用下面链接中的代码翻转像素图(仅在不将其转换为纹理,然后再转换为精灵时才能使用)。

https://dev59.com/umcs5IYBdhLWcg3w0HSz#19746741


1

你想创建一个FrameBuffer,frameBuffer.begin(),渲染所有内容,frameBuffer.end()。

然后你可以获取Pixmap。这包含了保存为任何图像文件所需的所有内容。


能否给一个示例代码,以及如何将其存储为图像的代码呢? - Ramiz Raja
同时,我在libgdx中使用OpenGL ES 1.0,并且FrameBuffer对于OpenGL ES 2.0是有效的。 - Ramiz Raja
我已经学习了ScreenUtils.getFrameBufferPixels()和ScreenUtils.getFrameBufferTexture(),但我不知道如何在Ligdx中将它们保存为图像。你能帮忙吗? - Ramiz Raja
1
这里有一个使用glReadPixels的例子:http://code.google.com/p/libgdx-users/wiki/Screenshots - Richard Taylor

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接