'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 1:[1]

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()
}

Solution 2:[2]

private fun Int.textDp(density: Density): TextUnit = with(density) {
    [email protected]()
}

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

Solution 3:[3]

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([email protected]()).toSp()  }

usage:

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

Solution 4:[4]

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

@Composable
fun Dp.textSp() = with(LocalDensity.current) {
    [email protected]()
}

val Dp.textSp: TextUnit
    @Composable get() =  with(LocalDensity.current) {
        [email protected]()
    }

Solution 5:[5]

You can:

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

val Int.dpTextUnit: TextUnit
    @Composable
    get() = with(LocalDensity.current) { [email protected]() } 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yannick
Solution 2 yong wei
Solution 3 kasra fallen
Solution 4 binrebin
Solution 5 Leonid Ivankin