Search code examples
javaopengllibgdxviewportaspect-ratio

Aspect Ratio for ShapeRender in LibGDX (OpenGL)


In LibGDX I am using a ShapeRenderer that produces a 10x10 square. To maintain aspect ratio I have applied the ExtendedViewport to an OrthographicCamera and set the stage to the ExtendedViewport.

public class Game extends ApplicationAdapter {  

private Viewport viewport;
private Stage stage;
private Camera camera;


@Override
public void create () {

camera = new OrthographicCamera(800, 480);
viewport = new ExtendViewport(800, 480, camera);
stage = new Stage(viewport);

In render() I call a shaperenderer, which should produce a square, but renders a y-stretched rectangle.

        shapeRenderer.begin(ShapeType.Filled);
        shapeRenderer.identity();
        shapeRenderer.setColor( Colors.get(square.color));          
        shapeRenderer.rect(square.x, square.y, square.width, square.height);
        shapeRenderer.end();

I am guessing that the problem is presumably that the ShapeRenderer is not registered with the stage. If I understand correctly, only actors can perform on stage and I cannot add primitive shapes.

I have fairly simple graphics objects that appear and disappear. Is it possible to avoid using a stage and still keep the aspect ratio or do I have to put the ShapeRender inside an actor? I would like to use the ExtendedViewport and not create my own method.

EDIT: There seems to be a bug in ExtendViewport. FitViewport does not stretch the objects.


Solution

  • Before shapeRenderer().begin, call shapeRenderer().setProjectionMatrix(camera.combined); This is also necessary for SpriteBatches.