I'm trying to count the number of characters displayed by a Text without rendering it. I thought I could use a TextMeasurer, however the number of "measured" characters is different than the number of characters I get if I render the actual Text.
This is the code I'm using:
val text= "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor " +
"incididunt ut labore et dolore magna aliqua. Tristique senectus et netus et malesuada. " +
"Pellentesque sit amet porttitor eget dolor. Accumsan sit amet nulla facilisi morbi tempus " +
"iaculis urna id."
val textStyle = TextStyle(
hyphens = Hyphens.Auto,
lineBreak = LineBreak.Paragraph
)
val maxLines = 2
BoxWithConstraints {
val textMeasurer = rememberTextMeasurer()
val measuredLayoutResult = textMeasurer.measure(
text = text,
style = textStyle,
maxLines = maxLines,
constraints = constraints,
)
val measuredCharacters = measuredLayoutResult.getLineEnd(measuredLayoutResult.lineCount - 1)
println("Measured characters : ${measuredCharacters}")
Text(
text,
style = textStyle,
maxLines = maxLines,
textAlign = TextAlign.Justify,
onTextLayout = { textLayoutResult ->
val actualCharacters = textLayoutResult.getLineEnd(textLayoutResult.lineCount - 1)
println("Actual characters : ${actualCharacters}")
},
)
}
I'm getting two different numbers:
- Measured characters : 124
- Actual characters : 128
Removing the textAlign makes the numbers equal. However that's not an option for me and I don't see a way to give the textAlign param to the measure function. Is there a way to do so?