栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

android中px和dp,px和sp之间的转换方法

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

android中px和dp,px和sp之间的转换方法

在Android开发中dp和px,sp和px之间的转换时必不可少的,网上流传的方法

public class DisplayUtils {
  
  public static int px2dp(Context context, float pxValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (pxValue / scale + 0.5f);
  }
  
  public static int dp2px(Context context, float dipValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dipValue * scale + 0.5f);
  }
  
  public static int px2sp(Context context, float pxValue) {
    final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
    return (int) (pxValue / fontScale + 0.5f);
  }
  
  public static int sp2px(Context context, float spValue) {
    final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
    return (int) (spValue * fontScale + 0.5f);
  }
}

关于转换公式中,通过类比一元一次函数,怎么看都是有问题的,这么明显的问题,为什么没人纠正,后来发现是自己并没有理解,原因是float类型在强转为int类型是,用的是去尾法,精度上有较大差异,所以通过+0.5f的方式,将去尾法转变成四舍五入法,提高精度。

调用TypedValue类实现转换


protected int dp2px(int dp){
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,getResources().getDisplayMetrics());
}

protected int sp2px(int sp){
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,getResources().getDisplayMetrics());
}
public class TypedValue {
  ...
  
  public static final int COMPLEX_UNIT_PX = 0;
  
  public static final int COMPLEX_UNIT_DIP = 1;
  
  public static final int COMPLEX_UNIT_SP = 2;
  
  public static final int COMPLEX_UNIT_PT = 3;
  
  public static final int COMPLEX_UNIT_IN = 4;
  
  public static final int COMPLEX_UNIT_MM = 5;
  
  public static float applyDimension(int unit, float value,
      DisplayMetrics metrics)
  {
    switch (unit) {
    case COMPLEX_UNIT_PX:
      return value;
    case COMPLEX_UNIT_DIP:
      return value * metrics.density;
    case COMPLEX_UNIT_SP:
      return value * metrics.scaledDensity;
    case COMPLEX_UNIT_PT:
      return value * metrics.xdpi * (1.0f/72);
    case COMPLEX_UNIT_IN:
      return value * metrics.xdpi;
    case COMPLEX_UNIT_MM:
      return value * metrics.xdpi * (1.0f/25.4f);
    }
    return 0;
  }
  ...
}

对比两种方式的差异,其实就在+0.5f上,去尾法和四舍五入法的区别,即精度问题。

总结

以上所述是小编给大家介绍的android中px和dp,px和sp之间的转换方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/156011.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号