Convert Dp to Px and Px to Dp in Android or Android Studio

In Android documentation ,

dp( Density-independent Pixels) - An abstract unit that is based on the physical density of the screen.These units are relative to a 160 dpi (dots per inch) screen, on which 1dp is roughly equal to 1px. When running on a higher density screen, the number of pixels used to draw 1dp is scaled up by a factor appropriate for the screen's dpi.

px(Pixels) - Corresponds to actual pixels on the screen. This unit of measure is not recommended because the actual representation can vary across devices; each devices may have a different number of pixels per inch and may have more or fewer total pixels available on the screen.

Here, we discussed about how to convert px to dp and dp to px,

public static int convertPixelToDp(int pixel, Context mContext) {
float pixels = pixel;
// Get the screen's density scale
final float scale = mContext.getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
return (int) (pixels * scale + 0.5f);

    public static int convertPixelsToDp(int px, Context context) {
Resources resources = context.getResources();
float dp = px * context.getResources().getDisplayMetrics().density;
return (Math.round(dp));
    public static int pxToDp(int px) {
return (int) (px / Resources.getSystem().getDisplayMetrics().density);

More you can learn about pixel and dp from
directly convent and see the values:

Happy Coding !!!

No comments:

Post a Comment


Most recent Elastic Search tutorials for beginner, intermediate and advance level developer, Yubraj Pokharel, in CodingWorkspace