Android中px与dip,sp与dip等的转换工具类
可以很好的处理分辨率在手机上问题,如单位转换等
1 public class DensityUtil { 2 3 public static final float getHeightInPx(Context context){ 4 final float height= context.getResources().getDisplayMetrics().heightPixels ; 5 return height; 6 } 7 public static final float getWidthInPx(Context context){ 8 final float width= context.getResources().getDisplayMetrics().widthPixels ; 9 return width; 10 } 11 public static final int getHeightInDp(Context context){ 12 final float height= context.getResources().getDisplayMetrics().heightPixels ; 13 int heightInDp = px2dip(context, height); 14 return heightInDp; 15 } 16 public static final int getWidthInDp(Context context){ 17 final float height= context.getResources().getDisplayMetrics().heightPixels ; 18 int widthInDp = px2dip(context, height); 19 return widthInDp; 20 } 21 22 23 /** 24 * 根据手机的分辨率从 dp 的单位 转成为 px(像素) 25 */ 26 public static int dip2px(Context context, float dpValue) { 27 final float scale = context.getResources().getDisplayMetrics().density ; 28 return (int) (dpValue * scale + 0.5f); 29 } 30 31 /** 32 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp 33 */ 34 public static int px2dip(Context context, float pxValue) { 35 final float scale = context.getResources().getDisplayMetrics().density ; 36 return (int) (pxValue / scale + 0.5f); 37 } 38 /** 39 * 将px值转换为sp 值,保证文字大小不变 40 * 41 * @param pxValue 42 * @param fontScale(DisplayMetrics类中属性scaledDensity) 43 * @return 44 */ 45 public static int px2sp(Context context, float pxValue) { 46 final float scale = context.getResources().getDisplayMetrics().density ; 47 return (int) (pxValue / scale + 0.5f); 48 } 49 50 /** 51 * 将sp值转换为px 值,保证文字大小不变 52 * 53 * @param spValue 54 * @param fontScale(DisplayMetrics类中属性scaledDensity) 55 * @return 56 */ 57 public static int sp2px(Context context, float spValue) { 58 final float scale = context.getResources().getDisplayMetrics().density ; 59 return (int) (spValue * scale + 0.5f); 60 } 61 }
鸡蛋,从外打破是食物,从内打破是生命。
人亦如是:从外打破是压力,从内打破是成长。
如果你等别人从外打破你,那么你注定是要成为别人的食物;
若是你自己从内打破,那么你会发现自己获得重生。

浙公网安备 33010602011771号