0

I'm an android developer in my kmp project I need the screen size :

expect object ScreenSize {
     val heightDp: Float
}

in android platform i implemented it like this :

actual object ScreenSize {
    actual val heightDp: Float
        get() = Resources.getSystem().displayMetrics.run { heightPixels / density }
}

in ios platform :

actual object ScreenSize {
    actual val heightDp: Float
        get() = UIScreen.mainScreen.bounds.size.height.toFloat
}

as i searched the above code should work but the .height is not known and is red and i can't get the width/height from the UIScreen.mainScreen.bounds.size

1 Answer 1

1

Solution for your code:
(I have included optional getters for other people too.)

import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.useContents
import platform.UIKit.UIScreen

@OptIn(ExperimentalForeignApi::class)
actual object ScreenSize {
    actual val widthDp: Float
        get() = UIScreen.mainScreen.bounds.useContents { size.width.toFloat() }

    actual val heightDp: Float
        get() = UIScreen.mainScreen.bounds.useContents { size.height.toFloat() }

    actual val density: Float
        get() = UIScreen.mainScreen.scale.toFloat()
}

I faced the the same issue today. You must use useContents {}

Tested on iOS, it correctly returns density now. If you multiply heightDp * scale (density) you will get a real screen pixel height.

Sign up to request clarification or add additional context in comments.

1 Comment

it worked thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.