Android中dp与px互相转化的工具类

前言

该工具类适配于kotlin开发,采用的扩展函数方式,使用更加简便,同时添加了不同类型的支持,后期显示相关内容的所需的工具类遇到了才会在这里逐个添加。

kotlin 复制代码
object DisplayUtils {
    private val density: Float
        get() = Resources.getSystem().displayMetrics.density

    private val scaledDensity: Float
        get() = Resources.getSystem().displayMetrics.scaledDensity

    
    // ========== px -> dp ==========
    fun Int.dp(): Int = (this / density).toInt()
    fun Float.dp(): Float = this / density

    // ========== dp -> px ==========
    fun Int.px(): Int = (this * density).toInt() //dp转
    fun Float.px(): Float = this * density

    // ========== px -> sp(文字)==========
    fun Int.sp(): Int = (this / scaledDensity).toInt()
    fun Float.sp(): Float = this / scaledDensity
}
相关推荐
jwn9992 小时前
Laravel5.x核心特性全解析
android·php·laravel
studyForMokey4 小时前
【Android面试】RecylerView专题
android·spring·面试
android_cai_niao6 小时前
Android中有什么技术过时了可以直接用新技术的
android·过时技术
lingggggaaaa6 小时前
PHP原生开发篇&文件安全&上传监控&功能定位&关键搜索&1day挖掘
android·学习·安全·web安全·php
我是场7 小时前
我的NPI项目 - OTA upgrade是什么?
android·人工智能
zh_xuan7 小时前
Android 实现fragment导航
android·fragment导航
java资料站7 小时前
MySQL 增量同步脚本
android·数据库·mysql
穷人小水滴7 小时前
手机安装 Cross Profile Test App (Android)
android·手机·一加
zh_xuan7 小时前
Android Paging 3实现分页加载
android·git·github·paging 3
天***88528 小时前
安卓KMPlayer安卓版播放器,支持AC-3、WMA、MP3、AAC
android·aac