Search code examples
kotlinandroid-jetpack-composedesktop

Jetpack Compose Desktop: getting your display's height and width


I am looking for a way to get your display's height and width in Jetpack Compose for Desktop, but despite the fact that I've found some questions on SO (Screen width and height in Jetpack Compose), it's not very helpful, because there are no values (and other stuff) such as LocalConfiguration, only - LocalViewConfiguration, which is a different thing.

So, some words about my initial goal: I want to be able to automatically change the size of font used in my application: textStyle = TextStyle(fontFamily = FontFamily.Monospace, fontSize = calculateRelativeFontSize()), where: @Composable fun calculateRelativeFontSize(): TextUnit { val height = ...; val width = ...; ...}

Finally, I'm sorry if I'm missing something, because I'm not really a Kotlin or (honestly) Jetpack Compose programmer, just was asked to do some stuff...

P.S. I'm working under Linux, so... maybe somehow (really don't believe in that)... (you got the point)


Solution

  • You have to remember that JetBrains Compose is built upon Skia and Java's AWT libraries. You can use their native functions relating to screen info. For instance using AWT:

    // CloudsAnimation.kt
    import org.jetbrains.skia.RuntimeEffect
    import java.awt.Toolkit
    
    @Composable
    fun CloudsAnimation(
        modifier: Modifier = Modifier
    ) {
        val screenSize = Toolkit.getDefaultToolkit().screenSize
        val screenHeight = screenSize.height
        val screenWidth = screenSize.width
        println("Width: $screenWidth ; Height: $screenHeight")
        // ... composables below etc
    
    }
    

    Running this on my 13 inch MacBook Pro :

    Width: 1440 ; Height: 900
    

    Edit: The awt imports are accessible in the source set jvmMain, since these apis are not available in commonMain. It is necessary to prepare actual/expect functions if you intend to use them in commonMain