1 public class DensityUtil { 2 /** 3 * 根据手机的分辨率从 dp 的单位 转成为 px(像素) 4 */ 5 public static int dip2px(Context context, float dpValue) { 6 final float scale = context.getResources().getDisplayMetrics().density; 7 return (int) (dpValue * scale + 0.5f); 8 } 9 10 /** 11 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp 12 */ 13 public static int px2dip(Context context, float pxValue) { 14 final float scale = context.getResources().getDisplayMetrics().density; 15 return (int) (pxValue / scale + 0.5f); 16 }