想来工作这么久,像素转换这一块从来都是直接跳过,需要的时候再去找转换公式,这样实在是不好,所以写个文章记录一下
android支持如下像素单位:px(像素)、in(英寸)、mm(毫米)、pt(磅,1/72英寸)、dp(与设备无关的显示单位)、dip(就是dp)、sp(用于设置字体大小),其中常用的就是px、dp和sp三种。
像素(px)表示的是手机屏幕上的一个个发光点,屏幕清晰度越高,表示单位面积下的像素点越多
dp,根据手机的像素密度(单位面积下像素点的比例)由系统计算出来的显示单位
dip,就是dp
sp,同dp相似,但还会根据用户的字体大小偏好来缩放(建议使用sp作为文本的单位,其它用dip)
dp和px的转换
dp和px之间的联系,取决于具体设备上的像素密度,像素密度就是DisplayMetrics里的density参数。当density=1.0时,表示一个dp值对应一个px值;当density=1.5时,表示两个dp值对应三个px值;当density=2.0时,表示一个dp值对应两个px值。
转换公式为:px/dp=density, dp=像素/像素密度
具体的转换函数如下所示:
/**
* 根据手机的分辨率从 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);
}
代码里面的加0.5f,其目的是四舍五入,因为浮点数强制转为整型时,小数点后面数值会被直接咔嚓掉,所以如果原小数位后大于0.5,再加0.5就会进一,就曲线实现了四舍五入。
px与sp互相转换
/**
* convert px to its equivalent sp
*
* 将px转换为sp
*/
public static int px2sp(Context context, float pxValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
/**
* convert sp to its equivalent px
*
* 将sp转换为px
*/
public static int sp2px(Context context, float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
}
同时系统也提供了TypedValue类帮助我们转换/**
* convert dp to its equivalent px
*/
protected int dp2px(int dp){
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,getResources().getDisplayMetrics());
}
/**
* convert sp to its equivalent px
*/
protected int sp2px(int sp){
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,getResources().getDisplayMetrics());
}