Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Converting pixels to dp

I have made my application with the height and width given in pixels for a Pantech gadget whose goal is 480x800.

I need to change over tallness and width for a G1 gadget.

I thought changing over it into DP will tackle the issue and give a similar answer for both devices.

Is there any simple method to change pixels over to dp?
by

2 Answers

rahul07
Java code:

// Converts 14 dip into its equivalent px
float dip = 14f;
Resources r = getResources();
float px = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dip,
r.getDisplayMetrics()
);

Kotlin code:

val dip = 14f
val r: Resources = resources
val px = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dip,
r.displayMetrics
)
kshitijrana14
Preferably put in a Util.java class
public static float dpFromPx(final Context context, final float px) {
return px / context.getResources().getDisplayMetrics().density;
}

public static float pxFromDp(final Context context, final float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}

Login / Signup to Answer the Question.