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.
Asked
Active
Viewed 4.0k times
61

Valeriy Katkov
- 33,616
- 20
- 100
- 123
2 Answers
162
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.

Valeriy Katkov
- 33,616
- 20
- 100
- 123
-
1Is AmbientDensity going to be called CompositionLocalDensity? (Actually, it's called `LocalDensity` now, I checked) – EpicPandaForce Feb 15 '21 at 12:28
-
@EpicPandaForce Thanks! Indeed, `Ambient`s are named `CompositionLocal`s since `alpha-12`, I've updated the answer – Valeriy Katkov Feb 15 '21 at 15:01
-
1great explanation of the syntax; i came here looking for precisely what sorcery that was! – user2297550 Feb 24 '21 at 15:27
-
9And if you want to convert from pixels to Dp, it's ```LocalDensity.current.run { 16.toDp() }``` – sea cat Nov 18 '21 at 13:09
-
1weird, it requires @Composable context for transforming dp to px. Why? – Michael Abyzov Aug 11 '22 at 12:08
-
What should I do in case of creating custom MeasurePolicy outside of @Composable context ? – Michael Abyzov Aug 11 '22 at 12:11
22
@Valeriy's answer is definitely the correct way to do it but if you want it slightly less verbose or you have a lot of converting to do you can create extension functions:
@Composable
fun Dp.dpToPx() = with(LocalDensity.current) { this@dpToPx.toPx() }
@Composable
fun Int.pxToDp() = with(LocalDensity.current) { this@pxToDp.toDp() }
This lets you convert your dp straight to px and vice versa.
val dpValue = 16.dp
val pxConverted = dpValue.dpToPx()
val pxValue = 100
val dpConverted = pxValue.pxToDp()

Oliver Metz
- 2,712
- 2
- 20
- 32