How to convert TextUnit to Dp in Jetpack Compose?

Viewed 4572

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.

5 Answers

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()
}
private fun Int.textDp(density: Density): TextUnit = with(density) {
    this@textDp.dp.toSp()
}

val Int.textDp: TextUnit
    @Composable get() =  this.textDp(density = LocalDensity.current)

I'm using these global functions for this:

functions:

@Composable
fun Float.dp() = with(LocalDensity.current) {  Dp(this@dp).toSp() }

@Composable
fun Int.dp() = with(LocalDensity.current) {  Dp(this@dp.toFloat()).toSp()  }

usage:

Text(
        text = lorem(2),
        color = Color.Red, maxLines = 1000, fontSize = 20f.dp()
    )

To convert Dp to Sp TextUnit use this extension from @yong wei's answer

@Composable
fun Dp.textSp() = with(LocalDensity.current) {
    this@textSp.toSp()
}

val Dp.textSp: TextUnit
    @Composable get() =  with(LocalDensity.current) {
        this@textSp.toSp()
    }

You can:

Text(fontSize = 20.dpTextUnit,
         text = "good good")

val Int.dpTextUnit: TextUnit
    @Composable
    get() = with(LocalDensity.current) { this@dpTextUnit.dp.toSp() } 
Related