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

Socheat KHAUV

05/24/2020, 11:58 PM
how to get screen width and screen height in a composable function?
a

alexzhukovich

05/25/2020, 5:29 AM
The simplest way is to use
ContextAmbient
for getting a
Context
and after it we can use
DisplayMetrics
. Code:
Copy code
val displayMetrics = DisplayMetrics()
(ContextAmbient.current as Activity)
    .windowManager
    .defaultDisplay
    .getMetrics(displayMetrics)

val widthPx = displayMetrics.widthPixels
val heightPx = displayMetrics.heightPixels
s

Socheat KHAUV

05/25/2020, 12:25 PM
Thanks @alexzhukovich
l

Leland Richardson [G]

05/25/2020, 2:30 PM
Is that really what you want, or are you just trying to figure out how much space your composable has to take up?
c

caelum19

05/25/2020, 6:08 PM
@Socheat KHAUV a handy helper here:
Copy code
@Composable
fun Dp.toPx(): Px = with(DensityAmbient.current) {
    return@toPx this@toPx.toPx()
}
for an easier time using in progress apis that may require px 🙂 just make sure you actually do need to use px though
s

Socheat KHAUV

05/26/2020, 10:20 AM
@Leland Richardson [G] - actually i wanted to display video and resize its width to be the same as screen width and maintaining its aspect ratio. below is my code. I am not sure is there another way to do it.
218 Views