9

I want to set the height of view in pixels not in dp.

 `Box(modifier = Modifier.height(100.dp))`

In this example height of the box is set to 100 dp and modifier function accepts only dp. How to set height of Box in pixel?

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
Evgeniy Rechkov
  • 465
  • 4
  • 15

2 Answers2

11

@Kilian it right, this can look like this:

Modifier.height(with(LocalDensity.current) { 100.toDp() })
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
  • 4
    I guess it works, but it's strange to first convert pixels to dips, and the system will then convert it back to pixels again... – Maarten Mar 16 '22 at 13:34
  • @Maarten I'd say it's odd to set the size to something other than DP. It's designed specifically to make the UI look as similar as possible across devices, and the use of pixels is rare. – Phil Dukhov Mar 16 '22 at 14:22
  • I often want to set the size of some dependent UI element in the hierarchy as a result `onSizeChanged`, which returns size in pixels. Do you suggest there is a better solution for me? – Maarten Mar 16 '22 at 14:38
  • @Maarten you can create an extension which will have my code underneath. – Phil Dukhov Mar 17 '22 at 03:35
2

You can use the toDp() method provided in the Density package.

See https://developer.android.com/reference/kotlin/androidx/compose/ui/unit/Density#(kotlin.Int).toDp() for more information.

Kilian
  • 275
  • 2
  • 8