获取屏幕DPI的正确方法

public static String getDisplayMetrics(Context cx) {
            String str = "";
            DisplayMetrics dm = new DisplayMetrics();
            dm = cx.getApplicationContext().getResources().getDisplayMetrics();
            int screenWidth = dm.widthPixels;
            int screenHeight = dm.heightPixels;
            float density = dm.density;
            float scaledDensity = dm.scaledDensity;
            int densityDpi = dm.densityDpi;
            float xdpi = dm.xdpi;
            float ydpi = dm.ydpi;
            str += "he absolute width of the display in pixels: " + String.valueOf(screenWidth) + "
";
            str += "The absolute height of the display in pixels: " + String.valueOf(screenHeight)
                            + "
";
            str += "The logical density of the display: " + String.valueOf(density)
                            + "
";
            str += "A scaling factor for fonts displayed on the display: " + String.valueOf(scaledDensity)
                                            + "
";
            str += "The screen density expressed as dots-per-inch: " + String.valueOf(densityDpi)
                                            + "
";
            str += "The exact physical pixels per inch of the screen in the X dimension: " + String.valueOf(xdpi) + "
";
            str += "The exact physical pixels per inch of the screen in the Y dimension: " + String.valueOf(ydpi) + "
";
            return str;
        }

在不同模器下执行的效果如下:



320*480的屏幕 hw.lcd.density=80

此种情况的疑问如下:density = 0.75 (这里不应该是80/160=0.5才对吗?)
scaledDensity = 0.75(同上)
densityDpi = 120(明明hw.lcd.density=80为何这里是120)
xdpi = 120(同上)
ydpi = 120(同上)




320*480的屏幕 hw.lcd.density=240

这种情况下正常,是我可以理解的结果。



320*480的屏幕 hw.lcd.density=320

此种情况的疑问如下:density = 1.5 (这里不应该是320/160=2才对吗?)
scaledDensity = 1.5(同上)
densityDpi = 240(明明hw.lcd.density=320为何这里是240)
xdpi = 240(同上)
ydpi = 240(同上)





480*800的屏幕 hw.lcd.density=240


此种情况的疑问如下:density = 1 (这里不应该是240/160=1.5才对吗?)
scaledDensity = 1(同上)
densityDpi = 160(明明hw.lcd.density=240为何这里是160)
xdpi = 164.75(同上)
ydpi = 165.20(同上)


以上是我的不理。不知道大家是如何理解的。。。

弄明白了,应该是模拟器的问题。如果一次启动多个模拟器,数据会串掉。 所以最好一次启动一个模拟器。

注解:density = getResources().getDisplayMetrics().density

这个值在不同密度的设备中返回不同的值:

160dpi:1

240dpi: 1.5

120dpi: 0.75

….类推

经验分享 程序员 微信小程序 职场和发展