Android 中dp 和px 转换及原理分析
public void setToDefaults() { widthPixels = 0; heightPixels = 0; density = DENSITY_DEVICE / (float) DENSITY_DEFAULT; densityDpi = DENSITY_DEVICE; scaledDensity = density; xdpi = DENSITY_DEVICE; ydpi = DENSITY_DEVICE; noncompatWidthPixels = widthPixels; noncompatHeightPixels = heightPixels; noncompatDensity = density; noncompatDensityDpi = densityDpi; noncompatScaledDensity = scaledDensity; noncompatXdpi = xdpi; noncompatYdpi = ydpi; } public static int DENSITY_DEVICE = getDeviceDensity(); private static int getDeviceDensity() { // qemu.sf.lcd_density can be used to override ro.sf.lcd_density // when running in the emulator, allowing for dynamic configurations. // The reason for this is that ro.sf.lcd_density is write-once and is // set by the init process when it parses build.prop before anything else. return SystemProperties.getInt("qemu.sf.lcd_density", SystemProperties.getInt("ro.sf.lcd_density", DENSITY_DEFAULT)); }/** * The reference density used throughout the system. */ public static final int DENSITY_DEFAULT = DENSITY_MEDIUM;/** * Standard quantized DPI for medium-density screens. */ public static final int DENSITY_MEDIUM = 160;
?
在 Resources.java 的构造函数里面调用DisplayMetrics 的setToDefaults 方法,使density 取值为DENSITY_DEVICE / (float) DENSITY_DEFAULT;
使density 最终的值和key:qemu.sf.lcd_density 和default_value:ro.sf.lcd_density 有关系,
系统里面一般并没有额外对key:qemu.sf.lcd_density 赋值,故取值ro.sf.lcd_density,而ro.sf.lcd_density 的值一般是在系统源码里面的设置好的了,比如:system.prop 里面可以设置该值.