How do I obtain the screen size in compose?
# compose
r
How do I obtain the screen size in compose?
l
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
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
Yes, this is better than my answer simple smile
r
Thank you all
j
@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