https://kotlinlang.org logo
#compose
Title
# compose
t

Tom De Decker

11/16/2023, 3:08 PM
Does anyone know whether it's possible to center the content of an annotated string when it contains spans with different font sizes? The use-case here would be to have text fields separated by a separator whose font size is quite a bit smaller than the rest of the content. As you can see in the screenshot, the text seems to have a shared baseline while I actually want them to have the same (vertical) center point. The alternative would be to have a row of text composables but that kind of feels like a waste.
z

Zach Klippenstein (he/him) [MOD]

11/16/2023, 8:49 PM
I don’t know if this is even possible with the platform text stack? But feel free to file a feature request
h

Halil Ozercan

11/16/2023, 11:13 PM
on platform you can use
baselineShift
on
TextPaint
to change how much you want to shift from the default baseline. This is actually also used by
baselineShift
attribute of SpanStyle in Compose. It's actually a multiplier in Compose that uses
ascent
as its coefficient. Ascent is a font metric that denotes the ascender line where most capital letters end. It's not usually enough to find the center of the line. However, you can find a multiplier that works for your case by trial and error.
Copy code
withStyle(
    style = SpanStyle(
        fontSize = smallFontSize,
        baselineShift = BaselineShift(0.3f)
    )
) {
    append(text)
}
positive multiplier pushes the text upwards, negative pulls it down.
t

Tom De Decker

11/17/2023, 9:32 AM
I've tried a few baseline shift values with the fonts we have to support and was able to settle on one that looks good with all of them. Thanks!
e

efemoney

11/17/2023, 11:18 AM
What did the final result look like?