如何在 Android Jetpack Compose 中将 Dp 转换为像素?

How to convert Dp to pixels in Android Jetpack Compose?

大部分 Jetpack Compose API 使用 Dp as a dimensions unit, but sometimes a pixel value is required. How can I convert a dp value to px? Just for an example there's graphicsLayer() 修饰符接受 translationX/Y 像素参数。

toPx() and roundToPx() methods defined by Density接口,你可以这样使用:

import androidx.compose.ui.platform.LocalDensity

val pxValue = with(LocalDensity.current) { 16.dp.toPx() }

// or

val pxValue = LocalDensity.current.run { 16.dp.toPx() }

如果您是 Kotlin 语言的新手,这样的表达式可能会让人感到困惑,所以让我们对其进行分解,看看它是如何工作的。 toPx() 是一个 extension function of Dp class, you can think of it as a Dp class method. But since toPx() is defined inside Density interface, you cannot use it unless you provide a density as a . And at last you can get the current density from an CompositionLocal named LocalDensity.