Android px与dip(dp)、px与sp单位的转换
首先分别介绍一下px、dp/dip、sp的区别:
px: pixels(像素). 不同设备显示效果相同,一般我们HVGA代表320×480像素,比较常用。
dp/dip:dp = dip : device independent pixels(设备独立像素).
不同设备有不同的显示效果,这个和设备硬件有关, 一般我们为了支持WVGA、HVGA和QVGA 推荐使用这个,不依赖像素。sp: scaled pixels(放大像素). 主要用于字体显示best for textsize。且google建议,TextView
的字号最好使用sp 做单位。
转换工具类:
/**
* 单位转换工具
*
* @author carrey
*
*/
public class DisplayUtil {
/**
* 根据手机的分辨率从 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);
}
/**
* 将px值转换为sp值,保证文字大小不变
*
* @param pxValue
* @param context
* DisplayMetrics类中属性scaledDensity
* @return
*/
public static int px2sp(Context context, float pxValue) {
final float fontScale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / fontScale + 0.5f);
}
/**
* 将sp值转换为px值,保证文字大小不变
*
* @param spValue
* @param context
* DisplayMetrics类中属性scaledDensity
* @return
*/
public static int sp2px(Context context,float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().density;
return (int) (spValue * fontScale + 0.5f);
}
}
如果此博文帮助到你,麻烦点个赞哈!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。