Is it possible to specify a Text size in Dp, inste...
# compose
d
Is it possible to specify a Text size in Dp, instead of Sp? This is very useful in elements like buttons, where the button size is fixed and you don't want the button text to grow if the user selects a bigger font in the device settings. In general, there are several layouts where you want text not to scale. It was possible in the Android view system to specify Dp text. Does Compose allow this?
m
You can convert Dp -> Pixel -> Sp using Density, then you should get the Sp value corresponding to the Dp value.
❤️ 1
d
Yes, that makes sense. Thanks!
@mohamed rejeb I have been using:
Copy code
val screenDensity = LocalDensity.current.density
val textSp = (screenDensity * textDp.value).sp
But actually the system font size settings doesn't affect the screenDensity. I would like to set the correct Sp, starting from a Dp value, based on the actual system font size settings. In other words, I would like the text to have the same size, no matter what is the system font size settings. Any idea?
OK, I found the fontScale settings too:
Copy code
val fontScale = LocalDensity.current.fontScale
val textSp = fontSize / fontScale
1
I created an extension function:
Copy code
fun TextUnit.scaleIndependent() : TextUnit {
    return this / LocalDensity.current.fontScale
}
so, I can convert easily any Sp to be scale independent:
Copy code
val fontSize = 14.sp.scaleIndependent()
r
Please remember that the font scale setting is, for many users, about accessibility and being able to use their device more comfortably or at all. Fixing the size of button labels can be a hindrance for them.
d
@romainguy you are right. I have been designing mobile apps for 15 years already. I am very aware of the accessibility issues. However there are some layout situations, where "locking" the size of the font has usability advantages without creating accessibility issues.
467 Views