http://www.cnblogs.com/zhouchanwen/archive/2012/10/20/2731984.html
在android内部会使用TypedValue.applyDimension函数将所有单位换算成px。
public static float applyDimension(int unit, float value,
DisplayMetrics metrics)
{
switch (unit) {
case COMPLEX_UNIT_PX:
return value;
case COMPLEX_UNIT_DIP:
return value * metrics.density;
case COMPLEX_UNIT_SP:
return value * metrics.scaledDensity;
case COMPLEX_UNIT_PT:
return value * metrics.xdpi * (1.0f/72);
case COMPLEX_UNIT_IN:
return value * metrics.xdpi;
case COMPLEX_UNIT_MM:
return value * metrics.xdpi * (1.0f/25.4f);
}
return 0;
}
public static float applyDimension (int unit, float value, DisplayMetrics metrics)
Since:
API Level 1
Converts an unpacked complex data value holding a dimension to its final floating point value. The two parameters unit and value are as in TYPE_DIMENSION
.
Parameters
unit | The unit to convert from. |
---|---|
value | The value to apply the unit to. |
metrics | Current display metrics to use in the conversion -- supplies display density and scaling information. |
Returns
- The complex floating point value multiplied by the appropriate metrics depending on its unit.
/**
* Android大小单位转换工具类
*
* @author wader
*
*/
public class DisplayUtil {
/**
* 将px值转换为dip或dp值,保证尺寸大小不变
*
* @param pxValue
* @param scale(DisplayMetrics类中属性density)
* @return
*/
public static int px2dip(float pxValue, float scale) {
return (int) (pxValue / scale + 0.5f);
}
/**
* 将dip或dp值转换为px值,保证尺寸大小不变
*
* @param dipValue
* @param scale(DisplayMetrics类中属性density)
* @return
*/
public static int dip2px(float dipValue, float scale) {
return (int) (dipValue * scale + 0.5f);
}
/**
* 将px值转换为sp值,保证文字大小不变
*
* @param pxValue
* @param fontScale(DisplayMetrics类中属性scaledDensity)
* @return
*/
public static int px2sp(float pxValue, float fontScale) {
return (int) (pxValue / fontScale + 0.5f);
}
/**
* 将sp值转换为px值,保证文字大小不变
*
* @param spValue
* @param fontScale(DisplayMetrics类中属性scaledDensity)
* @return
*/
public static int sp2px(float spValue, float fontScale) {
return (int) (spValue * fontScale + 0.5f);
}
}