转的别人的
原文地址:http://blog.csdn.net/sunboy_2050/article/details/6688883
android中获取屏幕的长与宽,参考了网上有很多代码,但结果与实际不符,如我的手机是i9000,屏幕大小是480*800px,得到的结果却为320*533
结果很不靠谱,于是自己写了几行代码,亲测一下
测试参数:
测试环境: i9000(三星)
物理屏幕:480*800px
density :1.5
测试代码:
- //
获取屏幕密度(方法1) - int
screenWidth = getWindowManager().getDefaultDisplay().getWidth(); // 屏幕宽(像素,如:480px) - int
screenHeight = getWindowManager().getDefaultDisplay().getHeight(); // 屏幕高(像素,如:800p) -
- Log.e(TAG
+ " getDefaultDisplay", "screenWidth=" + screenWidth + "; screenHeight=" + screenHeight); -
-
- //
获取屏幕密度(方法2) - DisplayMetrics
dm = new DisplayMetrics(); - dm
= getResources().getDisplayMetrics(); -
- float
density = dm.density; // 屏幕密度(像素比例:0.75/1.0/1.5/2.0) - int
densityDPI = dm.densityDpi; // 屏幕密度(每寸像素:120/160/240/320) - float
xdpi = dm.xdpi; - float
ydpi = dm.ydpi; -
- Log.e(TAG
+ " DisplayMetrics", "xdpi=" + xdpi + "; ydpi=" + ydpi); - Log.e(TAG
+ " DisplayMetrics", "density=" + density + "; densityDPI=" + densityDPI); -
- screenWidth
= dm.widthPixels; // 屏幕宽(像素,如:480px) - screenHeight
= dm.heightPixels; // 屏幕高(像素,如:800px) -
- Log.e(TAG
+ " DisplayMetrics(111)", "screenWidth=" + screenWidth + "; screenHeight=" + screenHeight); -
-