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
1 2 3 4 5 6 7 8 9 |
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.
http://developer.android.com/reference/android/util/TypedValue.html
1 |
float resultPix = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,1,getResources().getDisplayMetrics()) |
But for me the upper solution with px2Dp and dp2Px works perfect.