我有一个应用程序,想要在游戏屏幕上截取屏幕截图并保存为图片上传到Facebook。我正在使用Libgdx,并且我的重点是android。
有谁能帮我以编程方式截取游戏屏幕截图并将其保存为图像?
现在很容易做到。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;
}
}
简单解决方案:
Image screenShot = new Image(ScreenUtils.getFrameBufferTexture());
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());
你想创建一个FrameBuffer,frameBuffer.begin(),渲染所有内容,frameBuffer.end()。
然后你可以获取Pixmap。这包含了保存为任何图像文件所需的所有内容。
谢谢,我使用链接http://code.google.com/p/libgdx-users/wiki/Screenshots解决了它。但是我使用的是PixmapIO.writePNG(pixmap, fileHandle),而不是PNG.toPNG,因为它会出现没有PNG类的错误。
感谢Stick2的帮助。