LibGDX background image in FitViewport
So, I’m using LibGDX for my upcoming application.
I use FitViewport to ensure a 16:9 aspect ratio.
Therefore, players that use an aspect ratio other than 16:9 will have black bars on the website.
What is the best way to draw a screen fill background image that also covers the area where the black bar is located?
camera = new OrthographicCamera();
viewport = new FitViewport(WIDTH, HEIGHT, camera);
viewport.apply();
camera.position.set(WIDTH / 2, HEIGHT / 2, 0);
camera.update();
This is how I currently set up the camera/viewport.
Then I use SpriteBatch to draw something on it.
Gdx.gl.glClearColor(1, 1, 1, 1);
That’s how I’m currently changing the color of the black bars to at least any RGB color.
Solution
In my opinion, the best idea is to create a second stage with its own Viewport
for background purposes only. The second Viewport
shouldn’t be FillViewport – in my experience, it stretches your graph. I think ExtendViewport is better in this case.
So how it should look :
Stage stage, backStage;
FitViewport viewport;
ExtendViewport backViewport;
...
stage = new Stage(); this is your normal stage you have now
stage.setViewport( yourFitViewport ); here you are assingning fit viewport
backViewport = new ExtendViewport( screenWidth, screenHeight );
backStage = new Stage();
backStage.setViewport( backViewport );
...
now add to backStage your background Image
backStage.addActor( yourBackground );
Now you only need to work on the new stage in the rendering method.
backStage.act();
stage.act();
backStage.draw(); backStage first - we want it under stage
stage.draw();
And update the
new Viewport
in the update or render like the old one. That’s it.
Read more about Viewports
here: https://github.com/libgdx/libgdx/wiki/Viewports