Android Compose set height of view in pixels NOT in dp
Asked Answered
S

2

13

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?

Skip answered 10/9, 2021 at 18:31 Comment(0)
S
18

@Kilian it right, this can look like this:

Modifier.height(with(LocalDensity.current) { 100.toDp() })
Sibyls answered 11/9, 2021 at 4:49 Comment(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...Derina
@Derina 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.Sibyls
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?Derina
@Derina you can create an extension which will have my code underneath.Sibyls
E
3

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.

Euton answered 10/9, 2021 at 18:48 Comment(2)
I can't find this extension function. I'm using compose UI version 1.1.1Bohi
@OfekRegev use with(LocalDensity.current) { value.toDp() }Fining

© 2022 - 2024 — McMap. All rights reserved.