I am building a KMP project, and I need to calculate the screen width and display data accordingly.
How can I get the width in DP?
The current implementation does not give the correct width.
Common-
@Composable
expect fun getScreenWidth(): Dp
Android-
@Composable
actual fun getScreenWidth(): Dp = LocalWindowInfo.current.containerSize.width.dp
IOS-
@Composable
actual fun getScreenWidth(): Dp = LocalWindowInfo.current.containerSize.width.dp
To convert pixels to Dp
, you can leverage LocalDensity
:
import androidx.compose.ui.platform.LocalDensity
val sizeInDp = with(LocalDensity.current) { sizeInPixels.toDp() }
See the docs for more.