dp to px conversion in android

Frequently used code samples and tutorials
vivekkalady
Site Admin
Posts: 35
Joined: Tue Nov 18, 2014 2:39 pm

dp to px conversion in android

Postby vivekkalady » Wed Nov 19, 2014 3:34 pm

This is the formula

dp to px

Code: Select all

public int dpToPx(int dp) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));       
    return px;
}


px to dp

Code: Select all

public int pxToDp(int px) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    int dp = Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
    return dp;
}



  • dp: Density Independent Pixel, it varies based on screen density . In 160 dpi screen, 1 dp = 1 pixel. Except for font size, use dp always.
  • dip: dip == dp. In earlier Android versions dip was used and later changed to dp.
  • sp: Scale Independent Pixel, scaled based on user’s font size preference. Fonts should use sp.
  • px: our usual standard pixel which maps to the screen pixel.
  • in: inches, with respect to the physical screen size.
  • mm: millimeters, with respect to the physical screen size.
  • pt: 1/72 of an inch, with respect to the physical screen size.

Always use dp and sp only. sp for font sizes and dp for everything else. It will make UI compatible for Android devices with different densities.

Return to “Tutorials & Examples”

Who is online

Users browsing this forum: No registered users and 1 guest

cron