zoukankan      html  css  js  c++  java
  • dp px 转换工具

     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 }
  • 相关阅读:
    BZOJ1787 [Ahoi2008]Meet 紧急集合[结论题]
    poj3728 The merchant[倍增]
    poj2750 Potted Flower[线段树]
    poj2482 Stars in Your Window[扫描线]
    poj2182 Lost Cows[BIT二分]
    UVA12096 The SetStack Computer
    第05组(65) 需求分析报告
    团队介绍与选题报告
    数据采集技术第三次作业
    结对编程作业
  • 原文地址:https://www.cnblogs.com/xmb7/p/3190644.html
Copyright © 2011-2022 走看看