且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android 中 px和dp 的转换

更新时间:2022-06-08 08:50:36

安卓开发中,布局文件中我们习惯使用dp单位,但是很多java代码的api中默认使用的是px单位(如 setPadding、setButtom、setLeft 等),这就需要我们在很多场景下进行dp和px的转换。

代码片段如下:

public class DensityUtil {  
  
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素) 
     * 
     * @param context
     * @param dpValue
     * @return
     * @author SHANHY
     * @date   2015年10月28日
     */
    public static int dip2px(Context context, float dpValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (dpValue * scale + 0.5f);  
    }  
  
    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     * 
     * @param context
     * @param pxValue
     * @return
     * @author SHANHY
     * @date   2015年10月28日
     */
    public static int px2dip(Context context, float pxValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (pxValue / scale + 0.5f);  
    }  
}