如何在 jetpack 中正确旋转文本并使其进行正确的布局?当我使用rotate
文本对象上的修饰符会旋转文本,但布局中占用的大小似乎使用预旋转的文本宽度。
这是我想要完成的一个简单示例 - 垂直文本应该位于狭窄空间的左侧:
@Composable
fun MainBox() {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
modifier = Modifier.padding(4.dp).background(Color.Gray),
text = "This is at the top"
)
Row(
modifier = Modifier.fillMaxWidth().weight(1f),
verticalAlignment = Alignment.CenterVertically
) {
Text(
modifier = Modifier.padding(4.dp).rotate(-90f),
text = "This should be vertical text on the left side"
)
Text(
modifier = Modifier.fillMaxSize().background(Color.Yellow),
textAlign = TextAlign.Center,
text = "This is a big yellow box that should take up most of the space"
)
}
}
}
然而,这表明的就是这个。
如果我缩短垂直文本中的文本,它只会占用一个狭窄的空间,这看起来更像我想要的布局。
有没有一种方法可以拦截布局过程或用于固定大小的其他设置,以便垂直文本仅占用一个文本行的水平空间宽度,但仍然适应用户字体大小的变化(因此没有固定大小)?
类似问题的回答here https://stackoverflow.com/questions/62767755/how-to-stack-text-vertically-with-rotation-using-jetpack-compose and here https://stackoverflow.com/questions/66705884/make-a-row-of-rotated-text-in-jetpack-compose不解决这个问题或者不再工作。
我的版本。经过几次测试后似乎效果很好
class ComposeActivity7 : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeTutorialTheme {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
modifier = Modifier
.padding(4.dp)
.background(Color.Gray),
text = "This is at the top"
)
Row(
modifier = Modifier
.fillMaxWidth()
.weight(1f),
verticalAlignment = Alignment.CenterVertically
) {
Text(
modifier = Modifier
.vertical()
.rotate(-90f)
.background(Color.Gray)
.padding(4.dp),
text = "This should be vertical text on the left side"
)
Text(
modifier = Modifier
.fillMaxSize()
.background(Color.Yellow),
textAlign = TextAlign.Center,
text = "This is a big yellow box that should take up most of the space"
)
}
}
}
}
}
}
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)
)
}
}
Result
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)