DensityUtils.java
1.5 KB
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
package com.cnlive.gundam.video.utils;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.TypedValue;
/**
* 常用单位转换的辅助类
*/
public class DensityUtils {
private DensityUtils() {
/** cannot be instantiated **/
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* dp转px
*
* @param context
* @param dpVal
* @return
*/
public static int dp2px(@NonNull Context context, float dpVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dpVal, context.getResources().getDisplayMetrics());
}
/**
* sp转px
*
* @param context
* @param spVal
* @return
*/
public static int sp2px(@NonNull Context context, float spVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spVal, context.getResources().getDisplayMetrics());
}
/**
* px转dp
*
* @param context
* @param pxVal
* @return
*/
public static float px2dp(@NonNull Context context, float pxVal) {
final float scale = context.getResources().getDisplayMetrics().density;
return (pxVal / scale);
}
/**
* px转sp
*
* @param context
* @param pxVal
* @return
*/
public static float px2sp(@NonNull Context context, float pxVal) {
return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
}
}