1.屏幕參數(shù)
屏幕大小:指屏幕對角線的長度,通常用“寸”來度量。例如 5.5寸手機。(1英寸=2.54厘米)
分辨率:指手機屏幕的像素點個數(shù),例如720x1280,指寬有720個像素點,高有1280個像素點。
PPI:每英寸像素(Pixels Per Inch)又被稱為DPI(Dots Per Inch)。它是有對角線的像素點除以屏幕的大小得到的,通常達到400PPI就算是比較高的屏幕密度了。
2.獨立像素密度dp
Android系統(tǒng)使用mdpi即密度值為160的屏幕作為標準,在這個屏幕上1dp=1px,其他屏幕通過比例換算如下表。
| 寬×高(標準值) | 240×320 | 320×480 | 480×800 | 720×1280 | 1080×1920 | 1440×2560 |
|---|---|---|---|---|---|---|
| DPI等級 | LDPI | MDPI | HDPI | XHDPI | XXHDPI | XXXHDPI |
| DPI數(shù)值( | 120 | 160 | 240 | 320 | 480 | 640 |
| 對應比例 | 3 | 4 | 6 | 8 | 12 | 16 |
| 1DP=?PX (density) | 0.75 | 1 | 1.5 | 2 | 3 | 4 |
另:density和PPI的關系:density = ppi/160 = dpi/160
px = dp x density = dp x (dpi/160)
以上均為16:9的手機屏幕,18:9的手機主流分辨率為1080*2160
當控件在對應的文件夾中沒有找到,就從高分辨率的文件夾依次向低分辨率的文件夾中尋找
3.單位轉換工具類
public class DisplayUtil {
/**
* 根據(jù)手機的分辨率從 dp 的單位 轉成為 px(像素)
* <p>
* fontScale DisplayMetrics類中屬性 density
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根據(jù)手機的分辨率從 px(像素) 的單位 轉成為 dp
* <p>
* fontScale DisplayMetrics類中屬性 density
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
/**
* 根據(jù)手機的分辨率從 sp 的單位 轉成為 px(像素)
* <p>
* fontScale DisplayMetrics類中屬性 scaledDensity
*/
public static int sp2px(Context context, float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
/**
* 根據(jù)手機的分辨率從 px(像素) 的單位 轉成為 sp
* <p>
* fontScale DisplayMetrics類中屬性 scaledDensity
*/
public static int px2sp(Context context, float pxValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
/**
* dp2px
*/
public static int dpTopx(Context context, float dpValue) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dpValue,
context.getResources().getDisplayMetrics());
}
/**
* sp2px
*/
public static int spTopx(Context context, float spValue) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spValue,
context.getResources().getDisplayMetrics());
}
}