141

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;
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
Dawid Hyży
  • 3,581
  • 5
  • 26
  • 41

4 Answers4

397

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()
}
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
Vicky Chijwani
  • 10,191
  • 6
  • 56
  • 79
  • 1
    This is the correct answer: return px / (context.getResources().getDisplayMetrics().densityDpi / 160f) – android developer Aug 29 '16 at 20:05
  • 1
    @androiddeveloper, please explain why you think using densityDpi is better than density. – Ayaz Alifov Jul 27 '18 at 13:21
  • 1
    @SaQada Look at the docs: https://developer.android.com/reference/android/util/DisplayMetrics#density : "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. – android developer Jul 27 '18 at 20:49
  • `Resource.getSystem()` has no guarantee when multiple Displays exist. – EpicPandaForce Jan 29 '21 at 18:49
55
float ht_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, ht, getResources().getDisplayMetrics());
float wt_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, wt, getResources().getDisplayMetrics());
Vladimir
  • 3,774
  • 3
  • 23
  • 27
  • 19
    Question is about "px -> dp" , but the code looks like "dp -> px" ?? (note the '_px' suffix in LHS ) – Palani Apr 30 '13 at 14:14
  • This is converting the opposite way from question. – Jerry Destremps May 22 '14 at 01:50
  • 3
    any way you can change first parameter to `TypedValue.COMPLEX_UNIT_PX` from `TypedValue.COMPLEX_UNIT_DIP` so as to convert `dp-> px` – DeltaCap019 Jan 21 '16 at 11:09
  • 2
    @NullnVoid: That won't work. If you see the [docs for `TypedValue.applyDimension`](https://developer.android.com/reference/android/util/TypedValue.html#applyDimension(int,%20float,%20android.util.DisplayMetrics)), 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. – Vicky Chijwani Dec 03 '16 at 17:38
39

This should give you the conversion pixels -> dp:

DisplayMetrics displaymetrics = new DisplayMetrics();
int dp = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, myPixels, displaymetrics );
kaspermoerch
  • 16,127
  • 4
  • 44
  • 67
  • 48
    **What you're doing is a dp->px conversion.** [The docs for `TypedValue.applyDimension`](http://developer.android.com/reference/android/util/TypedValue.html#applyDimension%28int,%20float,%20android.util.DisplayMetrics%29) 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: http://stackoverflow.com/a/17880012/504611 – Vicky Chijwani Nov 13 '13 at 12:25
  • 1
    funny! Although it is not the real answer but it's still useful – Farshad Jun 23 '17 at 03:18
2
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());
NikhilReddy
  • 6,904
  • 11
  • 38
  • 58