Converting pixels to dp and dp to px in Android


If you play around with height and width for a android device you often need to convert between real pixel (px) and device indipenden pixel (dp, dip).

The following methods are a easy solution to convert between px to dp

	private float px2Dp(float px, Context ctx)
		return px / ctx.getResources().getDisplayMetrics().density;

	private float dp2Px(float dp, Context ctx)
		return dp * ctx.getResources().getDisplayMetrics().density;

The density equals the following values depending on your device type.

.75 on ldpi (120 dpi)
1.0 on mdpi (160 dpi; baseline)
1.5 on hdpi (240 dpi)
2.0 on xhdpi (320 dpi)
3.0 on xxhdpi (480 dpi)
4.0 on xxxhdpi (640 dpi)

Alternativ you can use a util from the android SDK to get pixel from dip.