s

    Socheat KHAUV

    2 years ago
    how to get screen width and screen height in a composable function?
    alexzhukovich

    alexzhukovich

    2 years ago
    The simplest way is to use
    ContextAmbient
    for getting a
    Context
    and after it we can use
    DisplayMetrics
    . Code:
    val displayMetrics = DisplayMetrics()
    (ContextAmbient.current as Activity)
        .windowManager
        .defaultDisplay
        .getMetrics(displayMetrics)
    
    val widthPx = displayMetrics.widthPixels
    val heightPx = displayMetrics.heightPixels
    s

    Socheat KHAUV

    2 years ago
    Thanks @alexzhukovich
    l

    Leland Richardson [G]

    2 years ago
    Is that really what you want, or are you just trying to figure out how much space your composable has to take up?
    caelum19

    caelum19

    2 years ago
    @Socheat KHAUV a handy helper here:
    @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

    2 years ago
    @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.