我知道如何将 Jetpack Compose 中的文本与基线对齐。
但是现在我需要对齐两个不同大小的文本,它们在 Row
中彼此跟随。由 ascent这两种字体中较大的一种。如果有意义的话,我想将其视为“按顶部基线”对齐两个文本。 Modifier.align(Alignment.Top)
不起作用,因为它不会通过上升对齐,而是通过布局的顶部对齐,然后文本在顶部没有正确对齐。
我试图看看如何做到这一点,但显然没有现成的功能或修饰符?我什至没有找到在 Compose 中访问 Text 的 ascent 属性等的方法。所以不确定这怎么可能?
感谢您的任何提示! :)
编辑 : 这是 Alignment.Top
时的样子用来。但我希望这两个文本在顶部对齐。
最佳答案
所有关于文本布局的信息都可以通过 onTextLayout
检索。 Text
争论。在这种情况下,您需要一个行大小,可以使用 getLineBottom
检索。 ,以及实际字体大小,可在 layoutInput.style.fontSize
中找到.
我同意如果你能用一些简单的方法来做这件事会更容易,所以我给你的feature request加了星标。 ,但现在你可以计算它:
onTextLayout = { textLayoutResult ->
val ascent = textLayoutResult.getLineBottom(0) - textLayoutResult.layoutInput.run {
with(density) {
style.fontSize.toPx()
}
}
},
对齐两个文本的完整示例:val ascents = remember { mutableStateMapOf<Int, Float>() }
val texts = remember {
listOf(
"Big text" to 80.sp,
"Small text" to 20.sp,
)
}
Row(
Modifier
.drawBehind {
ascents.maxOfOrNull { it.value }?.let {
drawLine(Color.Red, Offset(0f, it), Offset(size.width, it))
}
}
) {
texts.forEachIndexed { i, info ->
Text(
info.first,
fontSize = info.second,
onTextLayout = { textLayoutResult ->
ascents[i] = textLayoutResult.getLineBottom(0) - textLayoutResult.layoutInput.run {
with(density) {
style.fontSize.toPx()
}
}
},
modifier = Modifier
.alpha(if (ascents.count() == texts.count()) 1f else 0f)
.layout { measurable, constraints ->
val placeable = measurable.measure(constraints)
val maxAscent = ascents.maxOfOrNull { it.value } ?: 0f
val ascent = ascents[i] ?: 0f
val yOffset = if (maxAscent == ascent) 0 else (maxAscent - ascent).toInt()
layout(placeable.width, placeable.height - yOffset) {
placeable.place(0, yOffset)
}
}
)
}
}
结果:关于android - 在 Jetpack Compose 中按字体的上升而不是基线对齐两个文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70531951/