Most of Jetpack Compose API uses 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() modifier that accepts translationX/Y
arguments in pixels.
1 Answer
There're toPx()
and roundToPx()
methods defined by Density interface, you can use it like this:
import androidx.compose.ui.platform.LocalDensity
val pxValue = with(LocalDensity.current) { 16.dp.toPx() }
// or
val pxValue = LocalDensity.current.run { 16.dp.toPx() }
Such an expression might look confusing if you're new to Kotlin language so let's break it down and see how it works. toPx()
is an 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 receiver. And at last you can get the current density from an CompositionLocal named LocalDensity.
-
1Is AmbientDensity going to be called CompositionLocalDensity? (Actually, it's called
LocalDensity
now, I checked) Feb 15, 2021 at 12:28 -
@EpicPandaForce Thanks! Indeed,
Ambient
s are namedCompositionLocal
s sincealpha-12
, I've updated the answer Feb 15, 2021 at 15:01 -
1great explanation of the syntax; i came here looking for precisely what sorcery that was! Feb 24, 2021 at 15:27
-
5And if you want to convert from pixels to Dp, it's
LocalDensity.current.run { 16.toDp() }
– sea catNov 18, 2021 at 13:09