Android 中dp 和px 转换及原理分析

具体的转换方法如下,网上都是有的,但是自己看了之后感觉还是有点不明不白的,具体为什么呢,可以继续看后面.

/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

首先先列出来相关的方法:

Resources.java

public Resources(AssetManager assets, DisplayMetrics metrics,
            Configuration config, CompatibilityInfo compInfo) {
        mAssets = assets;
        mMetrics.setToDefaults();
        mCompatibilityInfo = compInfo;
        updateConfiguration(config, metrics);
        assets.ensureStringBlocks();
}

DisplayMetrics.java 相关方法

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 里面可以设置该值.

猜你喜欢

转载自862123204-qq-com.iteye.com/blog/2000289