LibGDX 屏幕截图奇怪的行为

LibGDX screenshot strange behaviour

我在 LibGDX 中遇到了截屏我的桌面应用程序的奇怪行为。我重新制作了一个小程序来重现这个 "bug",它只呈现黑色背景和红色矩形。这些图像是结果:

左边是window的屏幕剪辑工具的截图,这就是运行程序的样子。右边是我在下面发布的截图代码。澄清一下,我希望程序的屏幕截图获得左图的结果,而透明度不会变得很奇怪。

这是我的渲染代码,不要介意坐标。因为我可以看到矩形被完美渲染,所以错误出现在渲染方法中对我来说毫无意义。但我还是发了。

@Override
public void render() {

    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    Gdx.gl.glActiveTexture(GL20.GL_TEXTURE0);
    Gdx.gl.glEnable(GL20.GL_BLEND);
    Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);

    shape.begin(ShapeType.Filled);
    shape.setColor(Color.BLACK);
    shape.rect(0, 0, 300, 300);

    shape.setColor(1f, 0f, 0f, 0.5f);
    shape.rect(100, 100, 100, 100);
    shape.end();

    Gdx.gl.glDisable(GL20.GL_BLEND);

}

这是截图的代码:

public static void screenshot() {

    Pixmap pixmap = getScreenshot(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    PixmapIO.writePNG(new FileHandle(Gdx.files.getLocalStoragePath() + "screenshots/test.png"), pixmap);
    pixmap.dispose();

}

private static Pixmap getScreenshot(int x, int y, int w, int h) {
    final Pixmap pixmap = ScreenUtils.getFrameBufferPixmap(x, y, w, h);

    // 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;
}

我去研究了一下,我只发现了这个topic,这是完全相同的问题。不过,它的信息略少,也没有答案。希望有人能解开这个谜。

我的问题已在 2017 年 2 月 23 日Tenfour04 回答,但由于他没有兴趣将他的解决方案作为答案发布,我这样做是为了解决这个问题.非常感谢他。我所做的是将 getPixels() 返回的 ByteBuffer 中的每四个元素(alpha 值)设置为 (byte) 255 (不透明)这是我的结果:

private static Pixmap getScreenshot(int x, int y, int width, int height) {

    final Pixmap pixmap = ScreenUtils.getFrameBufferPixmap(x, y, width, height);

    ByteBuffer pixels = pixmap.getPixels();
    for(int i = 4; i < pixels.limit(); i += 4) {
        pixels.put(i - 1, (byte) 255);
    }

    int numBytes = width * height * 4;
    byte[] lines = new byte[numBytes];
    int numBytesPerLine = width * 4;
    for(int i = 0; i < height; i++) {
        pixels.position((height - i - 1) * numBytesPerLine);
        pixels.get(lines, i * numBytesPerLine, numBytesPerLine);
    }
    pixels.clear();
    pixels.put(lines);
    pixels.clear();

    return pixmap;
}