Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't toPx() work outside of Canvas in Jetpack Compose?

In the below code, toPx() works in Canvas but not in Surface.
Why?

Canvas(modifier = Modifier.size(16.dp)) {
    val textPaint = Paint().asFrameworkPaint().apply {
        textSize = 32.dp.toPx()
    }
}

Surface(modifier = Modifier.size(16.dp)) {
    val textPaint = Paint().asFrameworkPaint().apply {
        textSize = 32.dp.toPx() // Error `toPx()`
    }
}    
like image 568
Elye Avatar asked Sep 15 '25 16:09

Elye


1 Answers

The toPx() function is defined inside a Density interface and you cannot use it unless you provide it. The Canvas works with a DrawScope which provides it.

To use it you can provide the Density using theLocalDensity provider.
Something like:

val dpToPx = with(LocalDensity.current) { 32.dp.toPx() }
like image 98
Gabriele Mariotti Avatar answered Sep 17 '25 07:09

Gabriele Mariotti