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

本文详细介绍了Android开发中DP(dp)与PX(px)单位之间的转换方法,并深入探讨了转换背后的原理,包括如何利用手机分辨率进行单位换算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

/**
 * 根据手机的分辨率从 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 里面可以设置该值.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值