Java 实现 dp 转换成 px

1、使用 TypedValue.applyDimension 方法
float dpValue = 50f;

Log.i(TAG, "dpValue: " + dpValue);

float pxValue = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, getResources().getDisplayMetrics());

Log.i(TAG, "pxValue: " + pxValue);
# 输出结果

dpValue: 50.0
pxValue: 100.0
2、基于屏幕密度手动计算
float dpValue = 50f;

Log.i(TAG, "dpValue: " + dpValue);

float density = getResources().getDisplayMetrics().density;

Log.i(TAG, "density: " + density);

float pxValue = dpValue * density;

Log.i(TAG, "pxValue: " + pxValue);
# 输出结果

dpValue: 50.0
density: 2.0
pxValue: 100.0

Kotlin 实现 dp 转换成 px

1、使用 TypedValue.applyDimension 方法
val dpValue = 50f

println("dpValue: $dpValue")

val pxValue = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,
    dpValue,
    resources.displayMetrics
)

println("pxValue: $pxValue")
# 输出结果

dpValue: 50.0
pxValue: 100.0
2、基于屏幕密度手动计算
val dpValue = 50f

println("dpValue: $dpValue")

val density = resources.displayMetrics.density

println("density: $density")

val pxValue = dpValue * density

println("pxValue: $pxValue")
# 输出结果

dpValue: 50.0
density: 2.0
pxValue: 100.0
3、扩展函数
fun Float.dpToPx(): Float {
    return TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        this,
        Resources.getSystem().displayMetrics
    )
}

val dpValue = 50f

println("dpValue: $dpValue")

val pxValue = dpValue.dpToPx()

println("pxValue: $pxValue")
# 输出结果

dpValue: 50.0
pxValue: 100.0

封装成工具类

1、Java 实现
public class MyUnitTool {
    public static float dpToPx(Context context, float dpVlaue) {
        return TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                dpVlaue,
                context.getResources().getDisplayMetrics()
        );
    }
}
float dpValue = 50f;

Log.i(TAG, "dpValue: " + dpValue);

float pxValue = MyUnitTool.dpToPx(this, dpValue);

Log.i(TAG, "pxValue: " + pxValue);
# 输出结果

dpValue: 50.0
pxValue: 100.0
2、Kotlin 实现
object MyUnitToolKotlin {
    fun dpToPx(context: Context, dpValue: Float): Float {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dpValue,
            context.resources.displayMetrics
        )
    }
}
val dpValue = 50f

println("dpValue: $dpValue")

val pxValue = MyUnitToolKotlin.dpToPx(this, dpValue)

println("pxValue: $pxValue")
# 输出结果

dpValue: 50.0
pxValue: 100.0
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐