Device Display Metrics
Get the screens pixel dimensions
Section titled “Get the screens pixel dimensions”To retreive the screens width and height in pixels, we can make use of the WindowManagers display metrics.
// Get display metricsDisplayMetrics metrics = new DisplayMetrics();context.getWindowManager().getDefaultDisplay().getMetrics(metrics);These DisplayMetrics hold a series of information about the devices screen, like its density or size:
// Get width and height in pixelInteger heightPixels = metrics.heightPixels;Integer widthPixels = metrics.widthPixels;Get screen density
Section titled “Get screen density”To get the screens density, we also can make use of the Windowmanagers DisplayMetrics. This is a quick example:
// Get density in dpiDisplayMetrics metrics = new DisplayMetrics();context.getWindowManager().getDefaultDisplay().getMetrics(metrics);int densityInDpi = metrics.densityDpi;Formula px to dp, dp to px conversation
Section titled “Formula px to dp, dp to px conversation”DP to Pixel:
private int dpToPx(int dp){ return (int) (dp * Resources.getSystem().getDisplayMetrics().density);}Pixel to DP:
private int pxToDp(int px){ return (int) (px / Resources.getSystem().getDisplayMetrics().density);}