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
Why is there only ".sp" in fontSize of Text("") composable and not ".dp" in Jetpack Compose-beta08
Asked Answered
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.
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 –
Petitionary
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! –
Nasal
You can use extension properties:
private fun Int.textDp(density: Density): TextUnit = with(density) {
[email protected]()
}
val Int.textDp: TextUnit
@Composable get() = this.textDp(density = LocalDensity.current)
@Stable
val Int.tdp: TextUnit @Composable get() = textDp()
@Stable
val Double.tdp: TextUnit @Composable get() = textDp()
@Composable
private fun Int.textDp() = with(LocalDensity.current) { [email protected]() }
@Composable
private fun Double.textDp() = with(LocalDensity.current) { [email protected]() }
Use:
Text(
text = "My Text",
fontSize = 22.tdp,
color = Color.White
)
Welcome on StackOverflow. Can you edit your answer to add details and explain how it works and why it fix the issue from OP? –
Nevsa
© 2022 - 2024 — McMap. All rights reserved.
so that it doesnt change according to the system font.
doesn't sound very user friendly. what if i can't read your font size ? – AliquotfontSize
works with aTextUnit
. It can acceptsp
andem
– Malaguenaem
and it worked. – Petitionary