0.前言
Android 官方文档解释:
A structure describing general information about a display, such as its size, density, and font scaling. To access the DisplayMetrics members(描述显示信息的结构,诸如屏幕大小、屏幕密度和字体缩放)
获取DisplayMetrics使用下面代码
context.getResources().getDisplayMetrics();
1.获取DisplayMetrics对象
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
DisplayMetrics metrics1 = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(metrics1);
LUtil.d(TAG, ">>>>>>> metrics1 = " + metrics1);
DisplayMetrics metrics2 = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics2);
LUtil.d(TAG, ">>>>>>> metrics2 = " + metrics2);
DisplayMetrics metrics3 = this.getResources().getDisplayMetrics();
LUtil.d(TAG, ">>>>>>> metrics3 = " + metrics3);
2.获取屏幕大小、屏幕密度、字体缩放因子
DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();
float density = displayMetrics.density;
int dpi = displayMetrics.densityDpi;
float scaledDensity = displayMetrics.scaledDensity;
输出结果参考:
D: >>>>>>> metrics1 = DisplayMetrics{density=3.0, width=1080, height=2159, scaledDensity=3.0, xdpi=428.625, ydpi=428.553, densityDpi=480, noncompatWidthPixels=1080, noncompatHeightPixels=2159, noncompatDensity=3.0, noncompatDensityDpi=480, noncompatXdpi=428.625, noncompatYdpi=428.553}
D: >>>>>>> metrics2 = DisplayMetrics{density=3.0, width=1080, height=2159, scaledDensity=3.0, xdpi=428.625, ydpi=428.553, densityDpi=480, noncompatWidthPixels=1080, noncompatHeightPixels=2159, noncompatDensity=3.0, noncompatDensityDpi=480, noncompatXdpi=428.625, noncompatYdpi=428.553}
D: >>>>>>> metrics3 = DisplayMetrics{density=3.0, width=1080, height=2159, scaledDensity=3.4499998, xdpi=428.625, ydpi=428.553, densityDpi=480, noncompatWidthPixels=1080, noncompatHeightPixels=2159, noncompatDensity=3.0, noncompatDensityDpi=480, noncompatXdpi=428.625, noncompatYdpi=428.553}
3.使用DisplayMetrics在dp和px间转换
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
4.扩展
|