dp px変換ツール

7460 ワード

 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 }