How To Calculate Android Screen Aspect Ratio Mathematically
Solution 1:
DisplayMetricsmetrics= context.getResources().getDisplayMetrics();
floatratio= ((float)metrics.heightPixels / (float)metrics.widthPixels);
Solution 2:
To find ration in (16:9) you need to find the GCD and then divide both numbers by that.
intgcd(int p, int q) {
if (q == 0) return p;
elsereturn gcd(q, p % q);
}
voidratio(int a, int b) {
finalintgcd= gcd(a,b);
if(a > b) {
showAnswer(a/gcd, b/gcd);
} else {
showAnswer(b/gcd, a/gcd);
}
}
voidshowAnswer(int a, int b) {
System.out.println(a + " " + b);
}
After this just call ratio(1920,1080);
Solution 3:
I think i am very much late for this answer but still for the people who want to know, the answer is:
if(screen_width > screen_height)
{
aspectRatio = screen_width / screen_height;
}
else
{
aspectRatio = screen_height / screen_width;
}
Solution 4:
This is an old question, but none of the proposed answers was getting me quite the right ratio. After trying this out, I was able to get the right aspect ratio (e.g., Pixel 3a is 18.5/9 = 2.0555):
Kotlin:
val aspectRatio = window.decorView.height.toFloat() / window.decorView.width.toFloat()
Java:
float aspectRatio = ((float) getWindow().getDecorView().getHeight()) /
((float) getWindow().getDecorView().getWidth())
Solution 5:
...property seems to have only two values - long and notlong. I am trying to reverse engineer the logic being used by Android to classify a device as having one of the two aspect ratios.
For the record, there's no need to reverse engineer, just see https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/content/res/Configuration.java
// Is this a long screen?if (((longSizeDp*3)/5) >= (shortSizeDp-1)) {
// Anything wider than WVGA (5:3) is considering to be long.
screenLayoutLong = true;
} else {
screenLayoutLong = false;
}
So basically Android takes screen sizes in DP and the result is:
- long - screen with aspect ratio > 1.667 (5:3) - i.e. > WVGA
- notlong - screen with aspect ratio <= 1.667 (5:3) - i.e. <= WVGA
Example - Nexus 4 - 384 x 640 dp (5:3): long edge in dp: 640 short edge in dp: 384
Maths: 640 * 3 / 5 = 384 384 >= (384 - 1) -> false -> notlong
Post a Comment for "How To Calculate Android Screen Aspect Ratio Mathematically"