我正在开发一款游戏,需要我动态生成带有文本的卡片。为了实现这一目标,我尝试将通用卡片背景和一些文本渲染到帧缓冲区,然后从中创建一个纹理区域以用作 Sprite 。
上面的彩色大图像是下面函数返回的 Sprite 的样子。正在渲染的图像实际上是纹理图集从中加载 Sprite 的完整 Sprite 表。
第二张图像(这是预期的结果)是在函数结束时从像素图生成的 PNG 屏幕截图的内容。
我可以确认正在使用函数中生成的TextureRegion,因为更改fboRegion.flip()
的参数确实会影响生成的 Sprite 。
private Sprite generateCard(String text, TextureAtlas atlas){
//Create and configure font
BitmapFont font = new BitmapFont();
font.setColor(Color.RED);
//Create a SpriteBatch (Temporary, need to pass this in later)
SpriteBatch sb = new SpriteBatch();
//Create sprite from texture atlas
Sprite sprite = atlas.createSprite("back", 3);
//Create FrameBuffer
FrameBuffer fbo = new FrameBuffer(Pixmap.Format.RGBA8888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
//Extract Texture from FrameBuffer
TextureRegion fboRegion = new TextureRegion(fbo.getColorBufferTexture());
//Flip the TextureRegion
fboRegion.flip(false, true);
//Begin using the FrameBuffer (disable drawing to the screen?)
fbo.begin();
//Clear the FrameBuffer with transparent black
Gdx.gl.glClearColor(0f, 0f, 0f, 0f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
sb.begin();
//Draw card background
sb.draw(sprite, 0,0, sprite.getWidth(), sprite.getHeight());
//Draw card text
font.draw(sb, text, 20, 100);
sb.end();
//Take "Screenshot" of the FrameBuffer
Pixmap pm = ScreenUtils.getFrameBufferPixmap(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
PixmapIO.writePNG(new FileHandle("screenshot.png"), pm);
fbo.end();
sb.dispose();
fbo.dispose();
return new Sprite(fboRegion);
}
如果有人有任何建议,我将不胜感激。我觉得有些事情只是以错误的顺序发生,但我一生都看不到 FrameBuffer 可以从哪里获取它正在渲染的图像,或者为什么返回的 Sprite 有错误的图像,但将 FrameBuffer 转储到 PNG 会给出正确的图像。
最佳答案
经过相当多的额外实验,我发现上面的代码完全按照预期工作。我已经设法将问题追溯到其他一些代码,这些代码获取 Sprite 的尺寸和位置,但渲染不同的纹理(因此当我更改纹理区域时会发生翻转)。
感谢那些检查我的问题的人。
关于java - LibGDX FrameBuffer 到TextureRegion 正在渲染不正确的 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44557206/