如何使用 Jetpack Compose 垂直旋转堆叠文本?

问题描述 投票:0回答:4

尝试对齐文本元素,如下图所示:

如何在 Jetpack Compose 中执行此操作?

通常我会使用垂直方向的线性布局和带有

rotation of 90
的 TextView。想知道如何在撰写中实现这一目标。

android android-layout android-jetpack android-jetpack-compose
4个回答
10
投票

compose_版本:

1.0.0-beta02

要旋转元素,您可以使用

Modifier.rotate()
修饰符

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

3
投票

我没有找到旋转后有“wrap_content”的方法,但我希望它有帮助:

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)
    )
}

3
投票

来自 如何在 jetpack compose 中显示具有适当大小/布局的垂直文本的自定义修饰符的解决方案对我有用:

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)
        )
    }
}

用作

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

感谢Sergei S 的回答


0
投票

Sergei S 的答案的改进版本,将

rotate
vertical
修饰符合二为一,使其更易于使用

fun Modifier.rotateVertically(clockwise: Boolean = true): Modifier {
    val rotate = rotate(if (clockwise) 90f else -90f)
    
    val adjustBounds = 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)
            )
        }
    }
    return rotate then adjustBounds
}

像这样使用它:

Text(
    text = "I'm going to be rotated clockwise",
    modifier = Modifier.rotateVertically()
)
© www.soinside.com 2019 - 2024. All rights reserved.