Android菜鸟练习第二十一课 px与dip转换

  1. import android.content.Context;  
  2. //从手机获取的单位都是PX
  3. public class DensityUtil {    
  4.         
  5.     /**  
  6.      * 根据手机的分辨率从 dip 的单位 转成为 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==dip 
  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. }    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章