package com.hh.lib_base.utils;

import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Point;
import android.view.Display;
import android.view.WindowManager;

import com.hh.lib_base.BaseApplication;


/**
 *@Describe 屏幕分辨率工具
 *@author Xia WeiHao
 *@date 2021/9/18
 */
public class DensityUtil {

    /**
     *@Describe 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     *@author Xia WeiHao
     *@date 2021/9/18
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     *@Describe 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     *@author Xia WeiHao
     *@date 2021/9/18
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    @TargetApi(JELLY_BEAN_MR1)
    public static int getDisplayMetricsWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        int apiLevel = android.os.Build.VERSION.SDK_INT;
        Point outSize = new Point();
        if (apiLevel >= JELLY_BEAN_MR1) {
            display.getRealSize(outSize);
        } else {
            display.getSize(outSize);
        }
       return outSize.x;
    }

    @TargetApi(JELLY_BEAN_MR1)
    public static int getDisplayMetricsHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        int apiLevel = android.os.Build.VERSION.SDK_INT;
        Point outSize = new Point();
        if (apiLevel >= JELLY_BEAN_MR1) {
            display.getRealSize(outSize);
        } else {
            display.getSize(outSize);
        }
        return outSize.y;

    }

    public static int dp2px(Context context, float dp) {
        return (int) (getDensity(context) * dp + 0.5);
    }
    public static float getDensity(Context context) {
        return (context == null ? BaseApplication.getContext() : context).getResources().getDisplayMetrics().density;
    }
}
