本文转载于 http://blog.csdn.net/student9128/article/details/53932470
众所周知,在Android开发中dp和px,sp和px之间的转换时必不可少的,下面将转换的代码记录下来:
1 public class DisplayUtils { 2 /** 3 * convert px to its equivalent dp 4 * 5 * 将px转换为与之相等的dp 6 */ 7 public static int px2dp(Context context, float pxValue) { 8 final float scale = context.getResources().getDisplayMetrics().density; 9 return (int) (pxValue / scale + 0.5f); 10 } 11 12 13 /** 14 * convert dp to its equivalent px 15 * 16 * 将dp转换为与之相等的px 17 */ 18 public static int dp2px(Context context, float dipValue) { 19 final float scale = context.getResources().getDisplayMetrics().density; 20 return (int) (dipValue * scale + 0.5f); 21 } 22 23 24 /** 25 * convert px to its equivalent sp 26 * 27 * 将px转换为sp 28 */ 29 public static int px2sp(Context context, float pxValue) { 30 final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; 31 return (int) (pxValue / fontScale + 0.5f); 32 } 33 34 35 /** 36 * convert sp to its equivalent px 37 * 38 * 将sp转换为px 39 */ 40 public static int sp2px(Context context, float spValue) { 41 final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; 42 return (int) (spValue * fontScale + 0.5f); 43 } 44
同时系统也提供了TypedValue类帮助我们转换
1 /** 2 * convert dp to its equivalent px 3 */ 4 protected int dp2px(int dp){ 5 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,getResources().getDisplayMetrics()); 6 } 7 8 /** 9 * convert sp to its equivalent px 10 */ 11 protected int sp2px(int sp){ 12 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,getResources().getDisplayMetrics()); 13 }