2017-06-15 41 views
1

我正在製作一款遊戲,需要我動態生成帶有文字的卡片。爲了達到這個目的,我試圖將通用卡背景和一些文本渲染到幀緩衝區,然後從中創建一個TextureRegion用作Sprite。LibGDX FrameBuffer到TextureRegion呈現不正確的精靈

我現在試圖創建一些相當...意想不到的結果: This is the sprite that is returnedThis is what comes out of the PixMap screenshot

以上的大,色彩鮮豔的圖像就是通過下面的函數返回的精靈模樣。正在渲染的圖像實際上是紋理圖集加載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給出正確的圖像。

回答

0

所以經過一些額外的實驗後,我發現上面的代碼完全按照預期工作。我已經成功地將問題追蹤到其他一些代碼,這些代碼正在考慮精靈的尺寸和位置,但是渲染了不同的紋理(因此在更改紋理區域時翻轉過來)。

感謝那些檢查了我的問題。