# Device Display Metrics

# Get the screens pixel dimensions

To retreive the screens width and height in pixels, we can make use of the WindowManagers (opens new window) display metrics.

// Get display metrics
DisplayMetrics metrics = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(metrics);

These DisplayMetrics (opens new window) hold a series of information about the devices screen, like its density or size:

// Get width and height in pixel
Integer heightPixels = metrics.heightPixels;
Integer widthPixels = metrics.widthPixels;

# Get screen density

To get the screens density, we also can make use of the Windowmanagers (opens new window) DisplayMetrics (opens new window). This is a quick example:

// Get density in dpi
DisplayMetrics metrics = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(metrics);
int densityInDpi =  metrics.densityDpi;

# 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);
}