Andorid车机UI适配,AndroidUI图px的单位,如何适配1920x720,PPI100的屏幕设备

在 Android 开发中,针对 1920×720 分辨率、PPI 100 的屏幕设备进行 UI 适配,需要综合考虑 像素密度(PPI)屏幕尺寸 和 Android 的密度无关像素(dp) 体系。以下是完整的适配方案:


📌 1. 关键概念理解

(1) 屏幕参数计算

  • 分辨率:1920×720(横向像素 × 纵向像素)

  • PPI(Pixels Per Inch):100(每英寸像素数)

  • 屏幕尺寸(对角线)

    尺寸=19202+7202100≈2048100=20.48英寸尺寸=10019202+7202​​≈1002048​=20.48英寸

    (假设是 16:9 屏幕)

(2) Android 密度分类

PPI 范围密度类型Density(density比例
0 ~ 120ldpi0.75x3:4
120 ~ 160mdpi1x (基准)1:1
160 ~ 240hdpi1.5x3:2
240 ~ 320xhdpi2x2:1
320 ~ 480xxhdpi3x3:1
480+xxxhdpi4x4:1

本例:PPI=100 → 属于 ldpi(低密度)density=0.75


📌 2. 核心适配方案

(1) 使用 dp 替代 px

换算公式

dp=pxdensity=px0.75dp=densitypx​=0.75px​

  • 示例:设计稿中 100px → 代码中应写 133.33dp(因为 100 / 0.75 ≈ 133.33)。

<Button
    android:layout_width="133dp"  <!-- 设计稿 100px -->
    android:layout_height="67dp"  <!-- 设计稿 50px -->
    android:text="按钮" />

(2) 使用 sp 设置字体大小

<TextView
    android:textSize="16sp" />  <!-- 会随系统字体缩放 -->

📌 3. 针对 1920×720 (PPI 100) 的特殊处理

(1) 创建 values-ldpi 资源目录

在 res/values-ldpi/dimens.xml 中定义尺寸:

<resources>
    <!-- 设计稿 100px → 实际 133.33dp -->
    <dimen name="button_width">133dp</dimen>
    <dimen name="button_height">67dp</dimen>
</resources>

布局中使用

<Button
    android:layout_width="@dimen/button_width"
    android:layout_height="@dimen/button_height" />

(2) 使用 smallestWidth (sw) 适配

计算最小宽度(sw):

sw=min⁡(1920,720)density=7200.75=960dpsw=densitymin(1920,720)​=0.75720​=960dp

创建 res/values-sw960dp/dimens.xml 存放适配尺寸。


📌 4. 百分比布局(推荐 ConstraintLayout)

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintWidth_percent="0.5"  <!-- 宽度占屏幕 50% -->
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

📌 5. 代码动态计算(适用于特殊场景)

kotlin

// 将 px 转换为 dp
fun pxToDp(px: Int, context: Context): Int {
    val density = context.resources.displayMetrics.density
    return (px / density).toInt()
}

// 示例:设计稿 100px → 动态设置
button.layoutParams.width = pxToDp(100, context)

📌 6. 测试与验证

  • 使用 Android Studio 的模拟器,选择自定义设备(1920×720,PPI 100)。

  • 检查 DisplayMetrics

    kotlin

    val metrics = resources.displayMetrics
    Log.d("Screen", "密度: ${metrics.density}dpi, 宽度: ${metrics.widthPixels}px")

🚀 最佳实践总结

方法适用场景备注
dp / sp通用适配优先使用
values-ldpi低密度设备(PPI=100)覆盖 density=0.75 的情况
百分比布局复杂 UIConstraintLayout + Guideline
动态计算 dp特殊需求(如游戏 UI)代码中转换 px → dp

关键点

  1. PPI=100 → ldpi → density=0.75

  2. 设计稿 px 需按 dp = px / 0.75 转换

  3. 优先用 ConstraintLayout 百分比布局,避免硬编码尺寸。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值