2

I am trying to make a "Share Score" button in my game. Part of what I want to do as part of the score sharing is create a little graphic that has the game logo along with the user's score. This graphic will then be shared via whatever platform the user chooses. However, I am stuck on generating this graphic. Right now I have a base graphic that has the logo, but I need a way to draw text onto that graphic (i.e. draw the users score onto it) using libGDX.

In other words, is there a way to write text onto the a Pixmap in order to do this?

Thanks

Samuel M
  • 51
  • 1
  • 9

1 Answers1

4

You can use FrameBuffer object for your requirement then read block of pixels from the frame buffer using Gdx.gl.glReadPixels(...) in this way :

FrameBuffer frameBuffer;

SpriteBatch spriteBatch;
BitmapFont font;

TextureRegion bufferTextureRegion;
Texture texture;
OrthographicCamera cam;

@Override
public void create() {

    cam=new OrthographicCamera(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
    cam.setToOrtho(false);

    spriteBatch=new SpriteBatch();
    texture=new Texture("badlogic.jpg");
    font=new BitmapFont();

    int w=texture.getWidth();
    int h=texture.getHeight();

    frameBuffer=new FrameBuffer(Pixmap.Format.RGBA8888,Gdx.graphics.getWidth(), Gdx.graphics.getHeight(),false) ;
    frameBuffer.begin();

    Gdx.gl.glClearColor(0f,0f,0f,0f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    spriteBatch.begin();
    spriteBatch.draw(texture,0,0);
    font.draw(spriteBatch,"Score :100",100,100);
    spriteBatch.end();

    //bufferTextureRegion =new TextureRegion(frameBuffer.getColorBufferTexture(),0,0,frameBuffer.getWidth(),frameBuffer.getHeight());
    //bufferTextureRegion.flip(false,true);

    ByteBuffer buf;
    Pixmap pixmap = new Pixmap(w, h, Pixmap.Format.RGB888);
    buf = pixmap.getPixels();
    Gdx.gl.glReadPixels(0, 0, w, h, GL20.GL_RGB, GL20.GL_UNSIGNED_BYTE, buf);

    frameBuffer.end();

    PixmapIO.writePNG(Gdx.files.external("output.png"), pixmap);
}
Abhishek Aryan
  • 19,936
  • 8
  • 46
  • 65
  • This just worked for me ! The text was coming out upside down, so as a final step, I had to flip the image using `sprite.flip(false, true)` . – ether_joe Dec 14 '21 at 05:08