美文网首页
Android 不一样 DP 与 PX 转换

Android 不一样 DP 与 PX 转换

作者: FutureEye | 来源:发表于2021-07-20 21:15 被阅读0次

这是很不错的方式,我不懂为什么用的人那么少,今天就来用一下吧。

    public static  float dp2px(int values){
       return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,values, 
                Resources.getSystem().getDisplayMetrics());
    }

其中 TypedValue 是 Android 一个工具类,

/*
 unit 表示单位,  
COMPLEX_UNIT_PX
COMPLEX_UNIT_DIP
COMPLEX_UNIT_SP
COMPLEX_UNIT_PT
COMPLEX_UNIT_IN
COMPLEX_UNIT_MM
values: 表示要转化的值
DisplayMetrics:屏幕参数
*/
TypeValues.applyDimension(int unit,int values, DisplayMetrics dm)

为什么可以不用上下文环境呢?

Resources.getSystem() 这个类在 Android 源码中的解释:
/*
Return a global shared Resources object that provides access to only system
 resources (no application resources), is not configured for the current screen 
(can not use dimension units, does not change based on orientation, etc), 
and is not affected by Runtime Resource Overlay.
*/

这个方法可以提供与运行时无关的参数,比如屏幕的参数

相关文章

网友评论

      本文标题:Android 不一样 DP 与 PX 转换

      本文链接:https://www.haomeiwen.com/subject/cyvrmltx.html