Framebuffers allow users to render stuff to a texture instead of to the screen (= the backbuffer). This can prove useful in various ways, for example to perform post processing effects.

How to use framebuffers

Let’s create a FrameBuffer:

  1. FrameBuffer fbo = new FrameBuffer(Format.RGBA8888, 1024, 720, false);

Now, to render anything to the framebuffer, it has to be bound (via begin() and end()):

  1. fbo.begin();
  2. Gdx.gl.glClearColor(1, 1, 1, 1);
  3. Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
  4. batch.begin();
  5. batch.draw(anyCoolSprite, 0, 0);
  6. batch.end();
  7. fbo.end();

To retrieve the stuff rendered to the framebuffer, one has to call getColorBufferTexture():

  1. Texture texture = fbo.getColorBufferTexture();
  2. TextureRegion textureRegion = new TextureRegion(texture);
  3. textureRegion.flip(false, true);

As you can see above, the texture is flipped via use of a TextureRegion. This is done, because the framebuffer textures are generally upside-down.

If you just want to draw the framebuffer’s texture on screen, you can also use this to flip the texture:

  1. batch.draw(fbo.getColorTexture(), x, y, w, h, 0, 0, 1, 1)

Common Issues

Nesting

Please note, that the default framebuffers of libGDX cannot be nested (i.e. used inside of each other). This is due to FrameBuffer.end() always binding the back buffer, even if it wasn’t the previously bound buffer. A detailed description of this can be found here. To work around this problem, FrameBuffer can be extended and the end() method overridden. If you don’t want to implement this yourself, there are some community options.

Hdpi

If you’re having an hdpi display, rendering scene2d stuff inside of a framebuffer causes problems with clipping, which is used, for example, in dialogs. To fix this, either set the size of your framebuffer to the real pixel size (instead of the logical size):

  1. FrameBuffer fbo = new FrameBuffer(Format.RGBA8888, HdpiUtils.toBackBufferX(currentWidth), HdpiUtils.toBackBufferY(currentHeight), false);

or temporarily switch the hdpi mode:

  1. HdpiUtils.setMode(HdpiMode.Pixels);
  2. fbo.begin();
  3. stage.draw();
  4. fbo.end();
  5. HdpiUtils.setMode(HdpiMode.Logical);

Further resources