[代码片段]Android像素转换工具类

Android2个月前更新 改变自己
149 0 0
125啦读书导航,我的单页导航

前言

移动项目需要根据设备进行适配,这个还是很有用的,摘抄于此,方便自己查阅。

正文

public class DensityUtil {
    public static int dip2px(float dpValue) {
        return (int) (dpValue * Resources.getSystem().getDisplayMetrics().density + 0.5f * (float) (dpValue >= 0.0f ? 1 : -1));
    }

    public static int dimenDip2px(int dimenId) {
        return dip2px(Resources.getSystem().getDimension(dimenId) / Resources.getSystem().getDisplayMetrics().density);
    }

    public static int px2dip(float pxValue) {
        return (int) (pxValue / Resources.getSystem().getDisplayMetrics().density + 0.5f * (float) (pxValue >= 0.0f ? 1 : -1));
    }

    public static int px2sp(float pxValue) {
        return (int) (pxValue / Resources.getSystem().getDisplayMetrics().scaledDensity + 0.5f * (float) (pxValue >= 0.0f ? 1 : -1));
    }

    public static int sp2px(float spValue) {
        return (int) (spValue * Resources.getSystem().getDisplayMetrics().scaledDensity + 0.5f * (float) (spValue >= 0.0f ? 1 : -1));
    }
}

参考文章

  1. Android像素转换工具类
  2. 安卓工具类1——像素PX和dp互相转换的方法(获取手机屏幕尺寸PX)

© 版权声明
125啦读书导航,我的单页导航

相关文章

125啦读书导航,我的单页导航

暂无评论

暂无评论...