屏幕的參數
屏幕大小
屏幕對角線的大小,以寸來表示
分辨率
手機屏幕的橫豎像素點個數
屏幕密度ppi/dpi
對角線的像素點除以屏幕的大小
系統的屏幕大小
密度 | ldpi | mdpi | hdpi | xhdpi | xxhpi |
---|---|---|---|---|---|
密度值 | 120 | 160 | 240 | 320 | 480 |
分辨率 | 240*320 | 320*480 | 480*800 | 720*1280 | 1080*1920 |
獨立像素點
160:1dp = 1px
240:1dp = 1.5px
ldpi : mdpi : hdpi : xhdpi : xxhdpi = 0.75 : 1 : 1.5 : 2 : 3
單位的換算
//dp->px
public static int dp2px(Context context, int dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
//px->dp
public static int px2dp(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
//sp->px
public static int sp2px(Context context, float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
//px->sp
public static int px2sp(Context context, float pxValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
//TypedValue.applyDimension
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;
}