I’d like to measure the height of a block of text. I’m using TextMeasurer
for this purpose. The text will be 200dp wide and can span multiple lines. And thus, I’m setting a constraint with maxWidth = 200dp on the measure call.
@Preview
@Composable
private fun TextPreview() {
val density = LocalDensity.current
val text = "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog."
val textMeasurer = rememberTextMeasurer()
val measuredText = textMeasurer.measure(
text = text,
constraints = Constraints(
maxWidth = with(density) { 200.dp.toPx().toInt() }
)
)
val measuredTextHeight = with(density) { measuredText.size.height.toDp() }
MaterialTheme {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black)
) {
Box(
modifier = Modifier
.width(200.dp)
.height(measuredTextHeight)
.background(Color.Red)
)
Text(
text = text,
color = Color.White,
modifier = Modifier.width(200.dp)
)
}
}
}
Output screenshot below. The height of the red box represents the measured text height. As you can see, it’s much shorter than the actual text height as rendered in the Text
composable.
I would expect the height of the red box to match the height of the text in the Text
composable. Am I doing something wrong here?