码迷,mamicode.com
首页 > 移动开发 > 详细

Android 中 px和dp 的转换

时间:2015-10-28 19:26:12      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

安卓开发中,布局文件中我们习惯使用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);  
    }  
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

Android 中 px和dp 的转换

标签:

原文地址:http://blog.csdn.net/catoop/article/details/49469955

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!