Text(
modifier = Modifier
.fillMaxWidth()
.background(Color.Black),
minLines = 3,
textAlign = TextAlign.Center,
text = "Not centered vertically"
)
当当前行数少于最小行数时,如何按容器的垂直和水平方向居中文本?
The textAlign
属性仅定义如何水平对齐文本。
您可以使用TextMeasurer
测量文本并检查宽度是否 > 宽度text
。在这种情况下text
将占用超过 1 行Text
可组合的
在此示例中,我使用屏幕宽度(因为您使用的是fillMaxWidth()
).
val textMeasurer = rememberTextMeasurer()
val textLayoutResult: TextLayoutResult =
textMeasurer.measure(
text = AnnotatedString(text),
style = LocalTextStyle.current
)
val widthText = textLayoutResult.size.width
val density = LocalDensity.current
val configuration = LocalConfiguration.current
val screenWidth = density.run { configuration.screenWidthDp.dp.toPx()}
Text(
modifier = Modifier
.fillMaxWidth()
.background(Color.Black),
minLines = 3,
textAlign = TextAlign.Center,
text = if (widthText < screenWidth) "\n" + text else text,
color = White,
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)