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
}
相关推荐
_祝你今天愉快8 小时前
从驱动来分析服务的添加过程
android
Dovis(誓平步青云)10 小时前
折叠屏悬停看视频,上半屏和下半屏应该各做什么
android·java·服务器·开发语言·安全·音视频
alexhilton11 小时前
让架构边界变成可执行的测试
android·kotlin·android jetpack
hai_android13 小时前
SendChannel 与 ReceiveChannel 通信机制
android
数据治理自习室15 小时前
AI 应用评测体系(GraphRAG)
android·大数据·人工智能·kotlin
爱笑鱼15 小时前
Android 系统启动机制(五):system_server 是 init 启动的,还是 Zygote fork 出来的?
android
智购科技无人售货机工厂16 小时前
2026自动售货机防拆机物理安全设计:从安全螺丝到结构互锁的工程实践~YH
android·网络·驱动开发·python·单片机·安全·云原生
开开心心就好16 小时前
电子教鞭工具支持画框写字插图片功能齐全
android·开发语言·前端·javascript·人工智能·pdf·html
Dovis(誓平步青云)16 小时前
拍视频前先把镜头想清楚:做一个分镜取景辅助器
android·java·服务器·javascript·人工智能
峥嵘life17 小时前
Android16 系统 APEX 模块说明
android·大数据·开发语言