Android中dp和px之间进行转换

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

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

 

 

  1. import android.content.Context;  
  2.   
  3. public class DensityUtil {  
  4.   
  5.     /** 
  6.      * 根据手机的分辨率从 dp 的单位 转成为 px(像素) 
  7.      */  
  8.     public static int dip2px(Context context, float dpValue) {  
  9.         final float scale = context.getResources().getDisplayMetrics().density;  
  10.         return (int) (dpValue * scale + 0.5f);  
  11.     }  
  12.   
  13.     /** 
  14.      * 根据手机的分辨率从 px(像素) 的单位 转成为 dp 
  15.      */  
  16.     public static int px2dip(Context context, float pxValue) {  
  17.         final float scale = context.getResources().getDisplayMetrics().density;  
  18.         return (int) (pxValue / scale + 0.5f);  
  19.     }  
  20. }  

http://blog.csdn.net/arui319/article/details/6777133

posted @ 2014-05-04 03:44  daishuguang  阅读(277)  评论(0编辑  收藏  举报