Android: how to programmatically determine the exact pixel aspect ratio of a device?

I want to display tiles that are supposed to be all squares in my android app using OpenGL ES 2.0.

Is it possible for an app installed on an Android device to programmatically determine the exact aspect ratio of individual pixels of the device's screen without any user input?

+3


source to share


2 answers


I think you are looking for the DisplayMetrics class . It has heightPixels

and fields widthPixels

that give the screen dimensions as well as other useful information such as pixel density.



As mentioned in the documentation, you can get DisplayMetrics for your device using getWindowManager().getDefaultDisplay().getMetrics(metrics);

+4


source


I would not recommend using the xdpi and ydpi values ​​that you get from Display.getMetrics. These values ​​are known to be incorrect for some devices (for example, on the Huawei Ascend P1 I get xdpi and ydpi values ​​152.4 and 451.6 which are definitely far away, the pixels are much larger than that). If you try to draw a perfect square based on these incorrect values, you may end up with a highly stretched rectangle on some devices. At the moment the best advice I think is that pixels are square, which I understand is not an ideal situation. See https://groups.google.com/forum/#!topic/android-developers/g56jV0Hora0... Android platform code does not use these values. Instead, density and density DPI are used for x and y coordinates. You could even try to compare your xdpi and ydpi values, and if they differ significantly, then the default is square pixels, although I think that would be a messy solution as well.



+1


source







All Articles