Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the screen size of the device?

The desire have 480 x 800 pixels, 3.7 inches and the HD have 480 x 800 pixels, 4.3 inches screen specification.

I run the code that is accepted as answer from this thread How to get screen size of device? but it is wrong. For example for screen size of 3.7 inches returns 2.4 which is very wrong.

Does anybody know how to get the real screen size? I do not need the resolution I need the screen size of the screen in inches.

NOTE: this code is wrong (at lest doesn't work for me)

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels; //give me 320
int height = dm.heightPixels; //give me 533

I have HTC Desire and my resolution is 480 x 800 pixels,

Can someone please tell me how to get the real screen size in inches, and get the real resolution of the device?

like image 612
Lukap Avatar asked Jul 27 '11 07:07

Lukap


2 Answers

The code works fine but it doesn't return pixels, it returns DIP (Density independent pixels ) which is not the same.

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels; //320 dip
int height = dm.heightPixels; //533 dip

What I needed is the REAL pixels and the calculation for them is like this:

int widthPix = (int) Math.ceil(dm.widthPixels * (dm.densityDpi / 160.0));

now the widthPix is 480

like image 94
Lukap Avatar answered Oct 08 '22 20:10

Lukap


This is exactly what happens if you explicitly disable pre-scaling. See the second bullet point of this document (a quick Google search on the term "320x533" turned up lots of other people who've encountered this). Get rid of your pre-scaling and the discrepancy should go away (getWidth()/getHeight() would then return the actual size, not the scaled size.

Note for tablet devs: getWidth()/getHeight() will not return the raw screen size because the bottom bar (48 pixels or so) isn't part of the area an app can draw to. You'll get the size of everything you can draw to (e.g., 1280x752 rather than the full 1280x800 in landscape mode). Again, no pre-scaling means these values are accurate and exact.

like image 41
MartyMacGyver Avatar answered Oct 08 '22 19:10

MartyMacGyver