Android尺寸转换

public class DisplayUtils {
   /**
    * px值转换为dp    */
   public static int px2dp(Context context, float pxValue) {
      final float scale = context.getResources().getDisplayMetrics().density;
      return (int) (pxValue / scale + 0.5f);
   }

   /**
    * dp值转换为px    */
   public static int dp2px(Context context, float dpValue) {
      final float scale = context.getResources().getDisplayMetrics().density;
      return (int) (dpValue * scale + 0.5f);
   }

   /**
    * px值转换为sp    */
   public static int px2sp(Context context, float pxValue) {
      final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
      return (int) (pxValue / fontScale + 0.5f);
   }

   /**
    * sp值转换为px    */
   public static int sp2px(Context context, float spValue) {
      final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
      return (int) (spValue * fontScale + 0.5f);
   }

   /**
    * 获取屏幕宽度
    */
   public static int getScreenWidthPixels(Activity context) {
      DisplayMetrics metric = new DisplayMetrics();
      context.getWindowManager().getDefaultDisplay().getMetrics(metric);
      return metric.widthPixels;
   }

   /**
    * 获取屏幕高度
    */
   public static int getScreenHeightPixels(Activity context) {
      DisplayMetrics metric = new DisplayMetrics();
      context.getWindowManager().getDefaultDisplay().getMetrics(metric);
      return metric.heightPixels;
   }


}

你可能感兴趣的:(Android尺寸转换)