Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there only ".sp" in fontSize of Text("") composable and not ".dp" in Jetpack Compose-beta08

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

like image 564
Rishad Baniya Avatar asked Jun 10 '21 09:06

Rishad Baniya


2 Answers

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.

like image 117
Michał Klimczak Avatar answered Sep 28 '22 08:09

Michał Klimczak


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)
like image 28
yong wei Avatar answered Sep 28 '22 08:09

yong wei