6

I want the size of the text to be in .dp so that it doesn't change according to the system font. How to achieve this in Jetpack Compose "Text" composable

4

2 回答 2

8

The Compose team does not intend to provide that possibility, em are a bit pita to use, but there is an easy workaround should anyone really need it.

@Composable
fun dpToSp(dp: Dp) = with(LocalDensity.current) { dp.toSp() }

Text("ABCD", fontSize = dpToSp(15.dp))

Taken from the same issue tracker: https://issuetracker.google.com/190644747.

于 2021-06-15T13:46:08.820 回答
4

You can use extension properties:</p>

private fun Int.textDp(density: Density): TextUnit = with(density) {
    this@textDp.dp.toSp()
}


val Int.textDp: TextUnit
    @Composable get() =  this.textDp(density = LocalDensity.current)
于 2021-07-31T15:45:25.563 回答