I recently asked a question about this area that I think was too broad, so I will try a new approach.

I have the following code I am experimenting with:

        batch = new SpriteBatch();
        texture = new Texture(Gdx.files.internal("bg_test.png"));

        sprite = new Sprite(texture);
        sprite.setSize(GAME_WORLD_WIDTH, GAME_WORLD_HEIGHT);

        myGameWidth = Gdx.graphics.getWidth();
        myGameHeight = Gdx.graphics.getHeight();

        float aspectRatio = (float)myGameHeight / (float) myGameWidth;

        cam = new OrthographicCamera();
        viewport = new StretchViewport(GAME_WORLD_WIDTH * aspectRatio, GAME_WORLD_HEIGHT * aspectRatio, cam);
        cam.position.set(GAME_WORLD_WIDTH / 2, GAME_WORLD_HEIGHT / 2, 0);

Now I thought StretchViewport was supposed to stretch the image across whatever screen you tried, however I get this result in desktop when I try with config.height=800, config.width=400:

enter image description here

Now if I change the following line:

viewport = new StretchViewport(GAME_WORLD_WIDTH * aspectRatio, GAME_WORLD_HEIGHT * aspectRatio, cam);


viewport = new StretchViewport(GAME_WORLD_WIDTH, GAME_WORLD_HEIGHT, cam);

(I remove aspect ratio) This makes the image fill the screen the way I thought StretchViewport should, but I dont want to ignore the aspect ratio.

What makes it even weirder is that this only happens when I run desktop heigt>width(portrait), if I change it to the opposite width>height(landscape) then the image fills the screen too much, so the edges of the image go outside the screen :S

Am I missing something here? Is my aspectRatio wrong? I want to make sure my games will scale nicely across devices before I really get started with libgdx, right now all different viewports show me the same result with this padding.

I really can't figure this out, I get the behaviour (stretch) I want when I dont use aspectratio, but everywhere I read it tells me to use aspectratio. I really just wanna solve this so I can start with the fun stuff ^^


1 Answer 1


First your use of the aspect ratio is nonsense. The aspect ratio is the relation of width to height.

So if you have

float aspectRatio = (float)myGameHeight / (float) myGameWidth;

This means that the the following is true:

myGameHeight == aspectRatio * myGameWidth

If you want to preserve the aspect ratio of the screen you need to do the following:

viewport = new StretchViewport(GAME_WORLD_WIDTH, GAME_WORLD_WIDTH * aspectRatio, cam);

Note the that only GAME_WORLD_WIDTH is used. (If height is the desired size you want to preserve, do the inverse.)

  • \$\begingroup\$ Oh, I had no idea. Thanks for the good explenation :) \$\endgroup\$
    – Green_qaue
    Mar 19, 2015 at 14:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .