Aaronzzx
Aaronzzx

Reputation: 53

Jetpack Compose: TextAlign (Center vertically) of SpanStyle

How to implement Gravity.CENTER_VERTICAL when using SpanStyle?

Do not use other Container Composables like Box, Row, etc...

val spanString = buildAnnotatedString {
    withStyle(
        SpanStyle(
            color = Color(0xFF333333),
            fontSize = 32.sp
        )
    ) {
        append("Jetpack")
    }
    withStyle(
        SpanStyle(
            color = Color(0xFF999999),
            fontSize = 14.sp,
            fontWeight = FontWeight.Bold
        )
    ) {
        append(" Compose")
    }
}
Text(
    modifier = Modifier.background(color = Color.White),
    text = spanString
)

Now:
Img

Expect:
Img

Upvotes: 5

Views: 1331

Answers (1)

z.g.y
z.g.y

Reputation: 6257

Add this to your second SpanStyle

 baselineShift = BaselineShift.Superscript

Modified code

 val spanString = buildAnnotatedString {
        withStyle(
            SpanStyle(
                color = Color(0xFF333333),
                fontSize = 32.sp
            )
        ) {
            append("Jetpack")
        }
        withStyle(
            SpanStyle(
                baselineShift = BaselineShift.Superscript, // added line
                color = Color(0xFF999999),
                fontSize = 14.sp,
                fontWeight = FontWeight.Bold
            )
        ) {
            append(" Compose")
        }
    }
    Text(
        modifier = Modifier.background(color = Color.White),
        text = spanString,
        textAlign = TextAlign.Center
    )

enter image description here

Upvotes: 3

Related Questions