Thursday, March 21, 2013

Android: How to convert from dp to px? (example)

From dp to pixel:
 
private static int fromDp2Px(int dp, Context context) {
final Resources res = context.getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, res.getDisplayMetrics());
return (int) px;
}
 
or
 
private static int fromDp2Px(int dp, Context context) {
final Resources res = context.getResources();
DisplayMetrics metrics = res.getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return (int) px;
}
 
 
 
 
From pixel to dp:
 
private static int fromPx2Dp(int px, Context context) {
final Resources res = context.getResources();
DisplayMetrics metrics = res.getDisplayMetrics();
float dp = px / (metrics.densityDpi / 160f);
return (int) dp;
}

No comments:

Post a Comment