概述
因爲不同的屏幕具有不同的像素密度,因此同樣數量的像素在不同設備上可能對應於不同的物理尺寸。因此要使用
dp
和sp
單位。
dp
:是一種密度無關像素,對應於160dpi下像素的物理尺寸。
sp
:是相同的基本單位,但它會按用戶首選的文本尺寸進行縮放(屬於縮放無關像素),因此在定義文本尺寸時應使用此計量單位(但切勿爲佈局尺寸使用此單位)。
px
像素,屏幕上顯示數據的最基本的點。
dpi
dpi
(Dots Per Inch):每英寸的點數,也稱像素密度,即屏幕對角線像素值÷英寸值。
dpi.png
例:720x1280分辨率5.7英寸的手機:
dpi-calc.png
dp
dp
:在每英寸160點的顯示屏上,1dp = 1px,即px = dp(dpi / 160)
sp
sp
(Scaled Pixels):通常用於指定字體的大小,當用戶修改手機顯示的字體時,字體大小會隨之改變。
單位轉換
public class SizeUtil {
public static int dp2px(Context context, float dpValue) {
float density = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * density + 0.5f);
}
public static int sp2px(Context context, float spValue) {
float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
public static int px2dp(Context context, float pxValue) {
float density = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / density + 0.5f);
}
public static int px2sp(Context context, float pxValue) {
float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
}
使用TypedValue進行單位轉換
public static int dp2px(Context context, float dpValue) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources().getDisplayMetrics());
}
public static int sp2px(Context context, float spValue) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, context.getResources().getDisplayMetrics());
}
TypedValue.applyDimension
源碼:
public class TypedValue {
// ...
public static float applyDimension(int unit, float value, DisplayMetrics metrics) {
switch (unit) {
case COMPLEX_UNIT_PX:
return value;
case COMPLEX_UNIT_DIP:
return value * metrics.density;
case COMPLEX_UNIT_SP:
return value * metrics.scaledDensity;
case COMPLEX_UNIT_PT:
return value * metrics.xdpi * (1.0f/72);
case COMPLEX_UNIT_IN:
return value * metrics.xdpi;
case COMPLEX_UNIT_MM:
return value * metrics.xdpi * (1.0f/25.4f);
}
return 0;
}
// ...
}