androidandroid-layoutkotlinandroid-jetpackandroid-jetpack-compose

How to convert TextUnit to Dp in Jetpack Compose?


I know the difference between them. I want to calculate the text height base on lineHeight. The value of lineHeight is in TextUnit so I want to convert it into Dp.


Solution

  • You need to grab the current Density from the LocalDensity—so this will only work in composition, within a @Composable function—and use that to convert to Dp:

    val lineHeightSp: TextUnit = 12.sp
    val lineHeightDp: Dp = with(LocalDensity.current) {
         lineHeightSp.toDp()
    }