Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you calculate dp in pixels?

Dps and screen density A dp is equal to one physical pixel on a screen with a density of 160. To calculate dp: dp = (width in pixels *... A dp is equal to one physical pixel on a screen with a density of 160.

What is the equation that is used while developing native Android apps to convert dp units to pixel units?

px = (int)(dp * (displayMetrics.

How much dp is in an Android screen?

One dp is a virtual pixel unit that's roughly equal to one pixel on a medium-density screen (160dpi; the "baseline" density). Android translates this value to the appropriate number of real pixels for each other density.

What is dp in SP?

The terms DP and DIP refer to Density Independent Pixels, which are based on the physical density of the screen. SP: Similar to dp, but also scaled by the user's font size selection. When choosing font sizes, it is recommended that you use this unit so that they are adjusted for both screen density and user choice.


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()
}

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

This should give you the conversion pixels -> dp:

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

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());