Android开发中dp,sp和px之间的转换

众所周知,在Android开发中dp和px,sp和px之间的转换时必不可少的,下面将转换的代码记录下来:

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
public class DisplayUtils {

/**
* convert px to its equivalent dp
*
* 将px转换为与之相等的dp
*/
public static int px2dp(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}


/**
* convert dp to its equivalent px
*
* 将dp转换为与之相等的px
*/
public static int dp2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}


/**
* convert px to its equivalent sp
*
* 将px转换为sp
*/
public static int px2sp(Context context, float pxValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}


/**
* convert sp to its equivalent px
*
* 将sp转换为px
*/
public static int sp2px(Context context, float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
}

同时系统也提供了TypedValue类帮助我们转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14

/**
* convert dp to its equivalent px
*/
protected int dp2px(int dp){
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,getResources().getDisplayMetrics());
}

/**
* convert sp to its equivalent px
*/
protected int sp2px(int sp){
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,getResources().getDisplayMetrics());
}