Was there any consensus reached on "using dp inste...
# compose
d
Was there any consensus reached on "using dp instead of sp" for text? For example if I'm a bad guy and want to ignore font scaling settings, can I do that without repeating conversion each time?
k
Then you'll need to work a bit harder. No reason why a modern UI toolkit would make it easier for you to fight the user font scaling preference
👌 2
g
To be honest, the system font scaling is just unintelligent. If you for example already have huge text (as is the current fad for hero text), the system blows it up to the size of the Jupiter’s orbit. It’s in no way more accessible. So no matter what you do, you have to fight the system. We’ve opted for
dp
conversion, and a maximum font size that our layout supports (something like
40.dp
). I call that
SmartScaledText
because
CommonSenseScaledText
seems a bit passive aggressive.
âž• 1
😄 1
😆 1
Copy code
@Composable
fun SmartScaledText(
    text: String,
    style: TextStyle,
    modifier: Modifier = Modifier,
    maxSize: TextUnit = 40.sp
) {

    @Composable
    fun adjustTextStyle(style: TextStyle): TextStyle {

        @Composable
        fun getFontSizeToLimit(unit: TextUnit): TextUnit {

            if (unit == TextUnit.Unspecified)
                return unit

            fun getSystemFontScale(context: Context): Float {
                return try {
                    context.resources.configuration.fontScale
                } catch (e: Exception) {
                    1f
                }
            }

            val ctx = LocalContext.current
            val scale = remember { getSystemFontScale(ctx) }

            if (scale <= 1f)
                return unit

            val real = unit.times(scale)

            if (real.isSp && real.value > maxSize.value)
                return maxSize.times(1f / scale)

            return unit
        }

        val fontSize = getFontSizeToLimit(style.fontSize)
        val lineHeight = getFontSizeToLimit(style.lineHeight)
        return style.copy(fontSize = fontSize, lineHeight = lineHeight)
    }

    BasicText(text = text, modifier = modifier, style = adjustTextStyle(style))
}
Something like that.
d
Thanks. I understand why toolkit might refuse to allow this, but we also live in a world of tight budgets, managers/designers/projects not having money/incentive to draw all the possible layout variations, not enough devs/time to implement all this etc etc. In some scenarios not dealing with system's font scale is an [unfortunate] compromise one has to make.
I didn't realize that this can mostly be adjusted by having one custom
Text
and using it globally. Oh, and
TextField
also I guess