Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jetpack Compose: Find how many lines a text will take before composition

I am trying to determine how many lines a certain text will occupy on the screen before composition. Is there a way to do this?

like image 797
paxcow Avatar asked Sep 13 '25 11:09

paxcow


1 Answers

You can use onTextLayout on Text to get line count and some other features.

var lineCount = 1
Text(text= "", onTextLayout = {textLayoutResult: TextLayoutResult ->
    lineCount = textLayoutResult.lineCount
})

If you are using Jetpack Compose version 1.4.1 or above you can use TextMeasurer to measure text with any style you provide

    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)
    }
like image 159
Thracian Avatar answered Sep 16 '25 09:09

Thracian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!