14

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

Abhimanyu
  • 11,351
  • 7
  • 51
  • 121
Rishad Baniya
  • 665
  • 8
  • 14

2 Answers2

21

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.

Michał Klimczak
  • 12,674
  • 8
  • 66
  • 99
  • 3
    I was the one who asked that on issue tracker but forgot to update that answer here in stackoverflow; thank you for providing the code :D – Rishad Baniya Jun 15 '21 at 16:19
  • it is not easy to handle the interface when the user increases or decreases the font size. So this option is also somewhat reasonable. Thank you! – Đốc.tc May 10 '23 at 02:22
3

You can use extension properties:

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


val Int.textDp: TextUnit
    @Composable get() =  this.textDp(density = LocalDensity.current)
yong wei
  • 125
  • 1
  • 2