How to stack Text vertically with rotation using Jetpack Compose?

Viewed 2711

Trying to align text elements as shown in the image below:

enter image description here

How to do it in Jetpack Compose?

Normally I would use a Linear Layout with vertical orientation and TextViews with a rotation of 90. Wondering how to achieve this in compose.

3 Answers

compose_verion: 1.0.0-beta02

To rotate an element you can use Modifier.rotate() modifier

Column {
     Text(text = "text", modifier = Modifier.rotate(-90f))
     Text(text = "text", modifier = Modifier.rotate(-90f))
     Text(text = "text", modifier = Modifier.rotate(-90f))
}

I didn't find a way to have a "wrap_content" after rotation but I hope it helps:

Column (...) {
    Text("Element 1",
        style = TextStyle(textAlign = TextAlign.Center),
        modifier = Modifier
        .drawBackground(color = Color.Red)
        .padding(16.dp)
        .size(20.dp, 100.dp)
        .drawLayer(
            rotationZ = -90f
        )
        .size(100.dp, 20.dp)
    )
}

The solution with a custom modifier from How to show vertical text with proper size/layout in jetpack compose worked for me:

fun Modifier.vertical() = layout { measurable, constraints ->
    val placeable = measurable.measure(constraints)
    layout(placeable.height, placeable.width) {
        placeable.place(
            x = -(placeable.width / 2 - placeable.height / 2),
            y = -(placeable.height / 2 - placeable.width / 2)
        )
    }
}

Used as

Text(
    modifier = Modifier.vertical().rotate(-90f),
    text = "Vertical aligned element"
)

Credits to Sergei S's answer.

Related