简体   繁体   中英

fixing the resolution to 16:9

I'm trying to make an android game framework, I want to make it work on all possible screen resolutions by fixing the ration at 16:9, by taking some of the screen sides and make them blank if the ratio isn't 16:9 , I can't seem to be able to do the math behind it.

I tried to make a loop that takes subtract one each iteration and checks if the ratio became equal to 16:9, but the double division turns it in an infinite loop, because 1920:1080 != 16:9 for example

so can anyone give me a better way to do it?

or do you even suggest a resource that gives a better solution than making blank sides?

Ideally you want to be working with the width being as close as possible to the '16' of your desired 16:9 ratio.

Let's take an example of 480x320 ...

If you divide 480 / 16 the result is exactly 30. Multiplying 30 * 9 is 270. This means you can use the full width of 480 but you need to adjust the height as 270 is less than 320.

With a screen height of 320 pixels but a desired aspect ratio of 16:9 you need to create blank top and bottom margins with a total of 320 - 270 = 50. In order to get equal margin heights, divide by 2.

So...

480 / 16 = 30

30 * 9 = 270

320 - 270 = 50

50 / 2 = 25

Basically you can use full screen width but add a top and bottom margin of 25 pixels each.

EDIT: Now let's suppose you have an unusual screen size example 500x320 (unlikely but who knows?).

In this case we need to know what the modulus (remainder) is when we divide the screen width by 16...

int xPixels = 500; // Physical number of pixels on X axis
int yPixels = 320; // Physical number of pixels on Y axis
int leftMargin = 0;
int topMargin = 0;

// In the case of 500 width, the remainder will be 4 pixels
// because 500 / 16 is 31 with a remainder of 4.
int remainder = xPixels % 16;

// Check to see if the remainder is 0. If it's not then we need a left margin...
if (remainder != 0)
    leftMargin = remainder / 2;

// Now calculate height of the image
int imageHeight = xPixels / 16 * 9;

// Now check if image height is the same as the physical screen height
// if it's not then calculate the top margin
if (imageHeight != yPixels)
    topMargin = (yPixels - imageHeight) / 2;

With the above code you should be able to adjust the on-screen position based on top and left margins.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM