zoukankan      html  css  js  c++  java
  • DensityUtil【尺寸转换工具类(px、dp互相转换)】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处!

    前言

    用于项目中dp、px、sp之间的转换以及指定缩放值下的转换。

    效果图

    暂不需要

    代码分析

    常用的方法是px2dip、dip2px;

    px2dipRatio、dip2pxRatio方法的应用场景可以理解为一个占满全屏的控件,要求等比例缩放显示到占原屏幕0.95的容器中。此时,可以考虑 使用这两个方法对这个控件的宽度和高度值进行等比例缩放。

    使用步骤

    一、项目组织结构图

    注意事项:

    1、导入类文件后需要change包名以及重新import R文件路径

    2、Values目录下的文件(strings.xml、dimens.xml、colors.xml等),如果项目中存在,则复制里面的内容,不要整个覆盖

    二、导入步骤

     将DensityUtil文件复制到项目中即可。

    package com.why.project.densityutildemo.util;
    
    import android.content.Context;
    import android.util.DisplayMetrics;
    
    /**
     * Used 尺寸转换工具类(全)
     */
    public class DensityUtil {
        public static float RATIO = 0.95F;//缩放比例值
    
        /**
         * px 转 dp【按照一定的比例】*/
        public static int px2dipRatio(Context context, float pxValue) {
            float scale = getScreenDendity(context) * RATIO;
            return (int)((pxValue / scale) + 0.5f);
        }
    
        /**
         * dp转px【按照一定的比例】*/
        public static int dip2pxRatio(Context context, float dpValue) {
            float scale = getScreenDendity(context) * RATIO;
            return (int)((dpValue * scale) + 0.5f);
        }
    
        /**
         * px 转 dp
         * 48px - 16dp
         * 50px - 17dp*/
        public static int px2dip(Context context, float pxValue) {
            float scale = getScreenDendity(context);
            return (int)((pxValue / scale) + 0.5f);
        }
    
        /**
         * dp转px
         * 16dp - 48px
         * 17dp - 51px*/
        public static int dip2px(Context context, float dpValue) {
            float scale = getScreenDendity(context);
            return (int)((dpValue * scale) + 0.5f);
        }
    
        /**获取屏幕的宽度(像素)*/
        public static int getScreenWidth(Context context) {
            return context.getResources().getDisplayMetrics().widthPixels;//1080
        }
    
        /**获取屏幕的宽度(dp)*/
        public static int getScreenWidthDp(Context context) {
            float scale = getScreenDendity(context);
            return (int)(context.getResources().getDisplayMetrics().widthPixels / scale);//360
        }
    
        /**获取屏幕的高度(像素)*/
        public static int getScreenHeight(Context context) {
            return context.getResources().getDisplayMetrics().heightPixels;//1776
        }
    
        /**获取屏幕的高度(像素)*/
        public static int getScreenHeightDp(Context context) {
            float scale = getScreenDendity(context);
            return (int)(context.getResources().getDisplayMetrics().heightPixels / scale);//592
        }
        /**屏幕密度比例*/
        public static float getScreenDendity(Context context){
            return context.getResources().getDisplayMetrics().density;//3
        }
    
        /**获取状态栏的高度 72px
         * http://www.2cto.com/kf/201501/374049.html*/
        public static int getStatusBarHeight(Context context) {
            int statusHeight = -1;
            try {
                Class<?> aClass = Class.forName("com.android.internal.R$dimen");
                Object object = aClass.newInstance();
                int height = Integer.parseInt(aClass.getField("status_bar_height").get(object).toString());
                statusHeight = context.getResources().getDimensionPixelSize(height);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return statusHeight;
    
            //依赖于WMS(窗口管理服务的回调)【不建议使用】
            /*Rect outRect = new Rect();
            ((Activity)context).getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect);
            return outRect.top;*/
        }
    
        /**
         * 指定机型(displayMetrics.xdpi)下dp转px
         * 18dp - 50px*/
        public static int dpToPx(Context context, int dp) {
            return Math.round(((float)dp * getPixelScaleFactor(context)));
        }
    
        /**
         * 指定机型(displayMetrics.xdpi)下px 转 dp
         * 50px - 18dp*/
        public static int pxToDp(Context context, int px) {
            return Math.round(((float)px / getPixelScaleFactor(context)));
        }
    
        /**获取水平方向的dpi的密度比例值
         * 2.7653186*/
        public static float getPixelScaleFactor(Context context) {
            DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
            return (displayMetrics.xdpi / 160.0f);
        }
    }

    三、使用方法

    package com.why.project.densityutildemo;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    
    import com.why.project.densityutildemo.util.DensityUtil;
    
    public class MainActivity extends AppCompatActivity {
    
        private static final String TAG = "MainActivity";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            initData();
        }
    
        private void initData(){
            /**====================================DensityUtil========================================*/
            int screenWidth = DensityUtil.getScreenWidth(this);
            int screenHeight = DensityUtil.getScreenHeight(this);
            Log.w(TAG,"screenWidth="+screenWidth);
            Log.w(TAG,"screenHeight="+screenHeight);
    
            int dp = DensityUtil.px2dip(this,50);
            int px = DensityUtil.dip2px(this,dp);
            Log.w(TAG,"dp="+dp);
            Log.w(TAG,"px="+px);
    
            DensityUtil.RATIO = 0.95f;
            int dpRatio = DensityUtil.px2dipRatio(this,50);
            int pxRatio = DensityUtil.dip2pxRatio(this,dpRatio);
            Log.w(TAG,"dpRatio="+dpRatio);
            Log.w(TAG,"pxRatio="+pxRatio);
    
            int statusBarHeight = DensityUtil.getStatusBarHeight(this);
            Log.w(TAG,"barHeight="+statusBarHeight);
        }
    }

    打印日志如下:

     

    混淆配置

    参考资料

    Andorid获取状态栏高度

    http://www.2cto.com/kf/201501/374049.html

    项目demo下载地址

    https://github.com/haiyuKing/DensityUtilDemo

  • 相关阅读:
    协程初探
    属性传值
    分析代理模式
    上下文菜单与TrackPopupMenu
    走进小作坊(十六)----口碑营销
    线程池QueueUserWorkItem
    exosip
    Spark Core源代码分析: Spark任务运行模型
    微软2014校园招聘笔试试题
    怎样配置Tomcat环境变量
  • 原文地址:https://www.cnblogs.com/whycxb/p/6856733.html
Copyright © 2011-2022 走看看