我正在制作一款游戏,需要我动态生成带有文字的卡片。为了达到这个目的,我试图将通用卡背景和一些文本渲染到帧缓冲区,然后从中创建一个TextureRegion用作Sprite。LibGDX FrameBuffer到TextureRegion呈现不正确的精灵
以上的大,色彩鲜艳的图像就是通过下面的函数返回的精灵模样。正在渲染的图像实际上是纹理图集加载sprite所用的完整spritesheet。
第二个图像(这是预期的结果)是从像素图向函数结尾生成的PNG屏幕截图的内容。
我可以确认正在使用函数中生成的TextureRegion,因为更改fboRegion.flip()
的参数确实会影响生成的精灵。
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给出正确的图像。