How to calculate dp from pixels in android programmatically

105,479

Solution 1

All the answers here show a dp->px conversion rather than px->dp, which is what the OP asked for. Note that TypedValue.applyDimension cannot be used to convert px->dp, for that you must use the method described here: https://stackoverflow.com/a/17880012/504611 (quoted below for convenience).

fun Context.dpToPx(dp: Int): Int {
    return (dp * resources.displayMetrics.density).toInt()
}

fun Context.pxToDp(px: Int): Int {
    return (px / resources.displayMetrics.density).toInt()
}

Solution 2

float ht_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, ht, getResources().getDisplayMetrics());
float wt_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, wt, getResources().getDisplayMetrics());

Solution 3

This should give you the conversion pixels -> dp:

DisplayMetrics displaymetrics = new DisplayMetrics();
int dp = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, myPixels, displaymetrics );

Solution 4

DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        String str_ScreenSize = "The Android Screen is: "
                    + dm.widthPixels
                    + " x "
                    + dm.heightPixels;

        TextView mScreenSize = (TextView) findViewById(R.id.strScreenSize);
        mScreenSize.setText(str_ScreenSize);

can u cheeck it out..

or this may also help u

int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 
                     (float) 123.4, getResources().getDisplayMetrics());
Share:
105,479
Dawid Hyży
Author by

Dawid Hyży

Updated on July 08, 2022

Comments

  • Dawid Hyży
    Dawid Hyży almost 2 years

    I want to calculate dp from px programmatically. How to do it? I get resolution from:

    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    ht = displaymetrics.heightPixels;
    wt = displaymetrics.widthPixels;
    
  • Palani
    Palani about 11 years
    Question is about "px -> dp" , but the code looks like "dp -> px" ?? (note the '_px' suffix in LHS )
  • Vicky Chijwani
    Vicky Chijwani over 10 years
    What you're doing is a dp->px conversion. The docs for TypedValue.applyDimension say that the first argument is the unit to convert from, and the return value is the "complex floating point value multiplied by the appropriate metrics depending on its unit." applyDimension cannot be used to convert px->dp, for that you must do it as described here: stackoverflow.com/a/17880012/504611
  • Jerry Destremps
    Jerry Destremps about 10 years
    This is converting the opposite way from question.
  • Goldorak84
    Goldorak84 over 9 years
    This should be the accepted answer
  • user3290180
    user3290180 almost 9 years
    it's definitely the best answer I found about this problem. It's usable in every class.
  • DeltaCap019
    DeltaCap019 over 8 years
    any way you can change first parameter to TypedValue.COMPLEX_UNIT_PX from TypedValue.COMPLEX_UNIT_DIP so as to convert dp-> px
  • android developer
    android developer almost 8 years
    This is the correct answer: return px / (context.getResources().getDisplayMetrics().densityDpi / 160f)
  • Naveed Ahmad
    Naveed Ahmad over 7 years
    perfect answer Thanks
  • Vicky Chijwani
    Vicky Chijwani over 7 years
    @NullnVoid: That won't work. If you see the docs for TypedValue.applyDimension, it says: "Converts an unpacked complex data value holding a dimension to its final floating point value", i.e., the return value is always in px. So if you pass TypedValue.COMPLEX_UNIT_PX it will just do a px->px "conversion", which is to say, nothing.
  • Farshad Tahmasbi
    Farshad Tahmasbi about 7 years
    funny! Although it is not the real answer but it's still useful
  • kike
    kike almost 6 years
    Use toInt() method instead of casting for Kotlin.
  • Ayaz Alifov
    Ayaz Alifov almost 6 years
    @androiddeveloper, please explain why you think using densityDpi is better than density.
  • android developer
    android developer almost 6 years
    @SaQada Look at the docs: developer.android.com/reference/android/util/… : "The logical density of the display", "This value does not exactly follow the real screen size" , "To obtain the current density for a specific display, use densityDpi" . However, now that I've tested both ways, both seem to work fine. Just try to prefer float or double instead of int, because int might lose some precision on some cases. For example, try to convert the height to dp and back to px on QVGA, and you will get 319 instead of 320.
  • Ahamadullah Saikat
    Ahamadullah Saikat over 5 years
    The best solution ever.
  • EpicPandaForce
    EpicPandaForce over 3 years
    Resource.getSystem() has no guarantee when multiple Displays exist.