Linjiajia
2023-03-17 85e989454fcc64a3cd99eaf659e00c4a2c10b534
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.android.app_base.utils;
 
import android.content.Context;
 
import androidx.annotation.DimenRes;
 
/**
 * @author Ljj
 * @date 2023.03.13. 17:40
 * @desc 屏幕尺寸转化工具类
 */
public class ScreenSizeUtils {
 
    /**
     * 计算当前的SP的值
     * @param context
     * @param spSize :R.dimen.sp_16
     * @return
     */
    public static int getSP(Context context, @DimenRes int spSize){
 
        float pxValue = context.getResources().getDimension(spSize);//获取对应资源文件下的sp值
        //将px值转换成sp值
        return px2sp(context, pxValue);
    }
 
    /**
     * 计算当前的DP的值
     * @param context
     * @param dpSize :R.dimen.dp_16
     * @return
     */
    public  static int getDP(Context context,@DimenRes int dpSize){
        float pxValue = context.getResources().getDimension(dpSize);//获取对应资源文件下的sp值
        //将px值转换成sp值
        return px2dip(context, pxValue);
    }
 
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        if (context == null) {
            return (int) dpValue;
        }
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
 
    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        if (context == null) {
            return (int) pxValue;
        }
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
 
    /**
     * px转换为sp
     * @param context
     * @param pxValue
     * @return
     */
    public static int px2sp(Context context,float pxValue){
        if (context == null) {
            return (int) pxValue;
        }
        final float scale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / scale + 0.5f);
    }
}