Search code examples
javalibgdxviewportaspect-ratio

LibGDX: How to draw in the area of the black bars of a FitViewport?


I got a FitViewport with a virtual width and virtual height. When the screen got another aspect ratio than my virtual resolution black bars are added. I want to draw something inside these letterboxes.

I tried to do it that way, but only objects "inside" my virtual resolution are drawn, objects "outside" are just not visible:

viewport = new FitViewport(VIRTUAL_WIDTH, VIRTUAL_HEIGHT, cam);
viewport.apply();

batch.setProjectionMatrix(cam.combined);

batch.begin();
batch.draw(texture, viewport.getRightGutterX(), 0);
batch.end();

How to draw inside the letterboxes?


Solution

  • You would need a second viewport, probably ExtendViewport with the same virtual dimensions as your FitViewport.

    //create:
    fitViewport = new FitViewport(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);
    extendViewport = new ExtendViewport(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);
    
    //resize:
    fitViewport.update(width, height);
    extendViewport.update(width, height);
    
    //render:
    
    fitViewport.apply();
    batch.setProjectionMatrix(fitViewport.getCamera().combined);
    batch.begin();
    //draw game
    batch.end();
    
    extendViewport.apply();
    batch.setProjectionMatrix(extendViewport.getCamera().combined);
    batch.begin();
    //draw stuff in border
    batch.end();
    

    If you want to be sure the border stuff doesn't overlap your game, you could swap the draw order above.

    Or you could just use ExtendViewport to begin with for everything.