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