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:
px
Pixels - corresponds to actual pixels on the screen.in
Inches - based on the physical size of the screen.
1 Inch OR 2.54 centimetersmm
> Millimeters - based on the physical size of the screen.pt
> Points - 1/72 of an inch based on the physical size of the screen.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".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 whatsp
actually stands for, one doc says "scale-independent pixels", the other says "scaleable pixels".
From Understanding Density Independence In Android:
Density Bucket | Screen Density | Physical Size | Pixel Size |
---|---|---|---|
ldpi | 120 dpi | 0.5 x 0.5 in | 0.5 in * 120 dpi = 60x60 px |
mdpi | 160 dpi | 0.5 x 0.5 in | 0.5 in * 160 dpi = 80x80 px |
hdpi | 240 dpi | 0.5 x 0.5 in | 0.5 in * 240 dpi = 120x120 px |
xhdpi | 320 dpi | 0.5 x 0.5 in | 0.5 in * 320 dpi = 160x160 px |
xxhdpi | 480 dpi | 0.5 x 0.5 in | 0.5 in * 480 dpi = 240x240 px |
xxxhdpi | 640 dpi | 0.5 x 0.5 in | 0.5 in * 640 dpi = 320x320 px |
Related Topics
Couldn't Load Memtrack Module Logcat Error
How to Get the Height and Width of the Android Navigation Bar Programmatically
Error Opening Supportmapfragment for Second Time
Calculate Compass Bearing/Heading to Location in Android
Listview Click to Show Image in Imageview
How to Change the Color of Alertdialog Title and the Color of the Line Under It
Android - Implementing Search Filter to a Recyclerview
How to Use Searchview in Toolbar Android
Difference Between Android.App.Fragment and Android.Support.V4.App.Fragment
Android: Out of Memory Exception in Gallery
Latest Update on Enabling and Disabling Mobile Data Programmatically
Enable/Disable Data Connection in Android Programmatically
The Completest Cocos2D-X Tutorial & Guide List
Accessing Localhost of Pc from Usb Connected Android Mobile Device