• 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 }
  • 相关阅读:
    python常用函数 A
    从__name__=='__main__'说到__builtin__
    python常用魔法函数
    MySQL内核:InnoDB存储引擎 卷1
    “胡”说IC——菜鸟工程师完美进阶
    恶意代码分析实战
    转折点:移动互联网时代的商业法则
    大型网站系统与Java中间件实践
    《Node.js实战(双色)》作者之一——吴中骅访谈录
    网站运维技术与实践
  • 原文地址:https://www.cnblogs.com/xmb7/p/3190644.html
Copyright © 2020-2023  润新知