Formula Px to Dp, Dp to Px Android

Formula px to dp, dp to px android

Note: The widely used solution above is based on displayMetrics.density. However, the docs explain that this value is a rounded value, used with the screen 'buckets'. Eg. on my Nexus 10 it returns 2, where the real value would be 298dpi (real) / 160dpi (default) = 1.8625.

Depending on your requirements, you might need the exact transformation, which can be achieved like this:

[Edit] This is not meant to be mixed with Android's internal dp unit, as this is of course still based on the screen buckets. Use this where you want a unit that should render the same real size on different devices.

Convert dp to pixel:

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

Convert pixel to dp:

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

Note that there are xdpi and ydpi properties, you might want to distinguish, but I can't imagine a sane display where these values differ greatly.

How to convert DP, PX, SP among each other, especially DP and SP?

DP to PX:

public static int dpToPx(float dp, Context context) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());
}

SP to PX:

public static int spToPx(float sp, Context context) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.getResources().getDisplayMetrics());
}

DP to SP:

public static int dpToSp(float dp, Context context) {
return (int) (dpToPx(dp, context) / context.getResources().getDisplayMetrics().scaledDensity);
}

How to convert dp to pixels and and use it to draw to canvas in android

I think there's either a typo in your question or you really don't load the value for the height - you are actually loading a number representing the id of the resource. It should have been:

int buttonWidth = (int) dpToPixel(getResorces().getDimension(R.dimen.buttonHeight));

But...you don't need to do the transformation yourself:

getResources().getDimensionPixelSize(R.dimen.buttonHeight);

How to calculate dp from pixels in android programmatically

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

Android Convert Px to Dp (Video Aspect Ratio)

Instead of trying to infer the dp conversion factor from the screen's density classification, you can simply query it directly:

getWindowManager().getDefaultDisplay().getMetrics(metrics);
float logicalDensity = metrics.density;

logicalDensity will then contain the factor you need to multiply dp by to get physical pixel dimensions for the device screen.

int px = (int) Math.ceil(dp * logicalDensity);

Convert dip to px in Android

The formula is: px = dp * (dpi / 160), for having on a 160 dpi screen. See Convert dp units to pixel units for more information.

You could try:

public static int convertDipToPixels(float dips) {
return (int) (dips * appContext.getResources().getDisplayMetrics().density + 0.5f);
}

Hope this helps...

Converting dp to px without Context


is there some case where it might fail?

Yes, there is!

Android supports different screens, for example you might cast the app with Chromecast or connect to a different screen by other means. In that case the values will not be converted properly to that other screen.

From the documentation for Resources.getSystem():

Return a global shared Resources object that provides access to only
system resources (no application resources), and is not configured for
the current screen (can not use dimension units, does not change based
on orientation, etc).

What is the difference between px, dip, dp, and sp?

From the Android Developer Documentation:


  1. px

    Pixels - corresponds to actual pixels on the screen.


  2. in

    Inches - based on the physical size of the screen.

    1 Inch OR 2.54 centimeters


  3. mm

    > Millimeters - based on the physical size of the screen.


  4. pt

    > Points - 1/72 of an inch based on the physical size of the screen.


  5. dp or dip

    > Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160
    dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".


  6. sp

    > Scaleable Pixels OR scale-independent pixels - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommended you
    use this unit when specifying font sizes, so they will be adjusted
    for both the screen density and the user's preference. Note, the Android documentation is inconsistent on what sp actually stands for, one doc says "scale-independent pixels", the other says "scaleable pixels".

From Understanding Density Independence In Android:



Leave a reply



Submit