我正在製作一款遊戲,需要我動態生成帶有文字的卡片。爲了達到這個目的,我試圖將通用卡背景和一些文本渲染到幀緩衝區,然後從中創建一個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給出正確的圖像。