https://kotlinlang.org logo
#compose
Title
# compose
r

Rafs

11/27/2020, 11:57 AM
How do I obtain the screen size in compose?
l

loloof64

11/27/2020, 12:21 PM
Hi ! In my case, as I was using a Scaffold for the page, I did not have the whole screen size. But I think the process can be the same in your case. Please also not that the following recipe must be avoid at maximum
Copy code
WithConstraints {
val width = constraints.maxWidth
val height = constraints.maxHeight
}
See, if you can, a previous thread where someone gave me these advices.
☝️ 2
s

selcukbulca

11/27/2020, 12:25 PM
You can use
ConfigurationAmbient
to get screen width and height dp values, then convert them to pixels with
DensityAmbient
Copy code
val screenWidthDp = ConfigurationAmbient.current.screenWidthDp
        val screenHeightDp = ConfigurationAmbient.current.screenHeightDp
        val (screenWidthPx, screenHeightPx) = with(DensityAmbient.current) {
            screenWidthDp.dp.toPx() to screenHeightDp.dp.toPx()
        }
👎 3
👍 1
l

loloof64

11/27/2020, 12:26 PM
Yes, this is better than my answer simple smile
r

Rafs

11/27/2020, 12:27 PM
Thank you all
j

jim

11/27/2020, 4:53 PM
@loloof64 Don't sell yourself short; I actually like your answer better. Using the configuration ambient will tie yourself to Android and will make your composable unsuitable for things like unit testing (not to mention being able to reuse the composable in other contexts, like Desktop). As a general rule of thumb, ambients should be avoided anyway. Moreover, and most importantly of all, the behavior of
WithConstraints
is most likely what you're looking for. The composable should be reacting to the immediate space available, not to the number of pixels that the device happens to have; otherwise your composable will likely behave wrong when placed in a smaller context.
👍 10
4 Views