0
\$\begingroup\$

I have this method:

public final float aspectRatioHeight(float originalW, float originalH)
{
    float newHeight = (originalH / originalW) * (Gdx.graphics.getWidth()-20);
    return newHeight;
}

To calculate my an aspect ratio for the height of a sprite, but when i try run the app on an android device, the height still stretches out the app.

This is what im doing to set the size.

splashSprite.setSize(Gdx.graphics.getWidth() - 20, aspectRatioHeight(SW, SH) - 20);
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

The problem is that there's two aspect ratios to take into account. You have the aspect ratio of the screen with you're calculating in the aspectRatioHeight method, but there's also the aspect ratio of the image.

Consider a image that is 100x100 pixels, and you want to place that with a 10px margin on a screen that is 640x480. If you set the width of the sprite to 640-10-10=620px, what should the height be? What you're trying to do is to scale the sprite's height by the aspect ratio of the screen, which is this case is 480/640=0.75, but as the image is 100x100 and therefore has an apsect ratio of 1 that will skew it.

If you have a source image with an aspect ratio different that the target viewport you will have to accept one of these compromises;

  • Skew the image (but you don't want that)
  • Letter box the image, i.e pad the top/bottom or left/right with something (this happens when watching wide screen movies on a 4/3 TV, sometimes).
  • Stretch the image, by stretching you don't get the padding of letter boxing, but you'll miss some of the image as it stretches beyond the visible viewport.
\$\endgroup\$
2
  • \$\begingroup\$ What about scaling down? \$\endgroup\$
    – dan14941
    Dec 11, 2014 at 11:37
  • \$\begingroup\$ The math is the same for scaling up or down, it's a matter of projecting A on to B. Swap the figures around in my example, make the screen 100x100 and the image 640x480; you're never going to fill the entire screen with that image without accepting one of the compromises. If you set the width to 100px then the height should be 75px to keep the image's aspect ratio but then you have a 25px padding. \$\endgroup\$
    – bornander
    Dec 11, 2014 at 12:24

You must log in to answer this question.

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