无信号  
 1 public class DensityUtil {
 2     private final static String TAG = "DensityUtil";
 3     private static float density = 0f;
 4     private static float defaultDensity = 1.5f;// 高分辨率的手机density普遍接近1.5
 5 
 6     private DensityUtil() {   }
 7     
 8     public static void setDensity(float density) {
 9         DensityUtil.density = density;
10     }
11 
12     public static float getDensity(Context context) {
13         return  context.getResources().getDisplayMetrics().density;
14     }
15     
16     public static int getScreenWidth(Context context){
17         return context.getResources().getDisplayMetrics().widthPixels;
18     }
19     public static int getScreenHeight(Context context){
20         return context.getResources().getDisplayMetrics().heightPixels;
21     }
22     /**
23      * 根据手机的分辨率 dp 转成px(像素)
24      */
25     public static int dip2px(float dpValue) {
26         int px;
27         if (density == 0) {
28             Log.e(TAG,
29                     "density is invalid, you should execute DensityUtil.getDensity(Context context) first");
30             px = (int) (dpValue * defaultDensity + 0.5f);
31         } else {
32             px = (int) (dpValue * density + 0.5f);
33         }
34         XLog.i(TAG, "px = " + px);
35         return px;
36     }
37 
38     /**
39      * 根据手机的分辨率px(像素) 转成dp
40      */
41     public static int px2dip(float pxValue) {
42         int dp;
43         if (density == 0) {
44             Log.e(TAG,
45                     "density is invalid, you should execute DensityUtil.getDensity(Context context) first");
46             dp = (int) (pxValue / defaultDensity + 0.5f);
47         } else {
48             dp = (int) (pxValue / density + 0.5f);
49         }
50         XLog.i(TAG, "dp = " + dp);
51         return dp;
52     }
53 
54 }

 

posted on 2013-07-15 10:05  BenXian  阅读(9749)  评论(0编辑  收藏  举报