How to calculate dp from pixels in android programmatically [duplicate]
Asked Answered
M

4

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;
Mertiemerton answered 28/11, 2011 at 12:44 Comment(2)
Do you know the physical dimension of the screen? 7" in diemeter for example.Babu
Its annoying when its marked as a duplicate, but no link to the duplicate is attached to the duplicate notice.Tungstic
T
402

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://mcmap.net/q/36300/-converting-pixels-to-dp (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()
}
Torchbearer answered 13/11, 2013 at 12:31 Comment(4)
This is the correct answer: return px / (context.getResources().getDisplayMetrics().densityDpi / 160f)Bodwell
@androiddeveloper, please explain why you think using densityDpi is better than density.Saturday
@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.Bodwell
Resource.getSystem() has no guarantee when multiple Displays exist.Molini
G
56
float ht_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, ht, getResources().getDisplayMetrics());
float wt_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, wt, getResources().getDisplayMetrics());
Glidden answered 28/11, 2011 at 12:52 Comment(4)
Question is about "px -> dp" , but the code looks like "dp -> px" ?? (note the '_px' suffix in LHS )Lavatory
This is converting the opposite way from question.Garda
any way you can change first parameter to TypedValue.COMPLEX_UNIT_PX from TypedValue.COMPLEX_UNIT_DIP so as to convert dp-> pxSprag
@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.Torchbearer
G
39

This should give you the conversion pixels -> dp:

DisplayMetrics displaymetrics = new DisplayMetrics();
int dp = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, myPixels, displaymetrics );
Geosphere answered 28/11, 2011 at 12:49 Comment(2)
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: https://mcmap.net/q/36300/-converting-pixels-to-dpTorchbearer
funny! Although it is not the real answer but it's still usefulStatolatry
M
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());
Mattingly answered 28/11, 2011 at 12:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.