您的位置:首页 > 移动开发 > Android开发

Android中dp和px之间进行转换

2015-10-27 17:25 435 查看
2015-10-30 补充:

今天发现一个类

TypedValue

此类可以完美的帮助我们完成单位转换的问题。

比如,

1、代码中设置字体大小(sp)

setTextSize(TypedValue.COMPLEX_UNIT_SP, size);


2、获得dp对应的px大小

public float getRawSize(int unit, float value){

Resources res = this.getResources(); 

return TypedValue.applyDimension(unit, value, res.getDisplayMetrics()); 

}

———————————————————————————————————————————————————————————

原文链接:http://blog.csdn.net/arui319/article/details/6777133

在xml布局文件中,我们既可以设置px,也可以设置dp(或者dip)。一般情况下,我们都会选择使用dp,这样可以保证不同屏幕分辨率的机器上布局一致。但是在代码中,如何处理呢?很多控件的方法中都只提供了设置px的方法,例如setPadding,并没有提供设置dp的方法。这个时候,如果需要设置dp的话,就要将dp转换成px了。

以下是一个应用类,方便进行px和dp之间的转换。

import android.content.Context;  

  

public class DensityUtil {  

  

    /** 

     * 根据手机的分辨率从 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);  

    }  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: