What is the SpanStyle equivalent of RelativeSizeSpan?

Viewed 192

In Compose, we use AnnotatedString as a replacement for Spanned. However, I cant seem to find a way to replicate the behaviour of RelativeSizeSpan with a SpanStyle.

The relevant options I can see for SpanStyle are:

  • fontSize: TextUnit - not useful because this only accepts absolute text sizes, and I need my span style to scale the original font size by some factor
  • textGeometricTransform: TextGeometricTransform - not useful because TextGeometricTransform only performs X transformations, and I need the text to be scaled in both X and Y.

Can anyone share some insight?

1 Answers

You can achieve it with SpanStyle, but you need to use the em TextUnit, which is a relative font size unit. It means that 1em is equal to the current font size and 2em is a font two times bigger.

Here is the code demonstrating how it behaves on two Texts with different font size:

val annotatedString = buildAnnotatedString {
    append("This is a ")
    withStyle(style = SpanStyle(fontSize = 2.em)) {
        append("big")
    }
    append(" text")
}
Column {
    Text(annotatedString, fontSize = 20.sp)
    Text(annotatedString, fontSize = 40.sp)
}

The word big is 2 times bigger than other words in the same Text.
You can also see that it makes the big word from first Text the same size (2 * 20sp) as the other words in the second Text (40sp).

enter image description here

Related