pax*_*cow 13 android-jetpack-compose
我试图确定某个文本在合成之前将在屏幕上占据多少行。有没有办法做到这一点?
Thr*_*ian 27
您可以使用onTextLayoutonText来获取行数和一些其他功能。
var lineCount = 1
Text(text= "", onTextLayout = {textLayoutResult: TextLayoutResult ->
lineCount = textLayoutResult.lineCount
})
Run Code Online (Sandbox Code Playgroud)
如果您使用的是 Jetpack Compose 1.4.1 或更高版本,您可以使用 TextMeasurer 来测量您提供的任何样式的文本
val textMeasurer = rememberTextMeasurer()
val textToDraw = "Some text to measure\nSomething something"
val style = TextStyle(
fontSize = 150.sp,
color = Color.Black,
background = Color.Red.copy(alpha = 0.2f)
)
// You can get many information since it's TextLayoutResult as in callback
val textLayoutResult = remember(textToDraw) {
textMeasurer.measure(textToDraw, style)
}
Run Code Online (Sandbox Code Playgroud)
虽然接受的答案是正确的,但还有一种替代方法,它甚至不需要可组合函数:
val paragraph = androidx.compose.ui.text.Paragraph(
text = "Foo",
style = MaterialTheme.typography.body1,
constraints = Constraints(maxWidth = maxWidthInPx),
density = LocalDensity.current,
fontFamilyResolver = LocalFontFamilyResolver.current,
)
paragraph.lineCount
Run Code Online (Sandbox Code Playgroud)
如果需要事先知道 lineCount,这可能更适合。
| 归档时间: |
|
| 查看次数: |
5918 次 |
| 最近记录: |