Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compose Text - width in chars

Is there a way to tell a Text composable to be as wide as e.g. 2 characters no matter what the provided text is?

I want to have a row with weights and some fixed size cells but I do want the fixed size cells to have a width that's exactly as large as it needs to be to contain n characters of the provided font...

like image 836
prom85 Avatar asked Sep 03 '25 02:09

prom85


1 Answers

You can use the TextMeasurer to measure a text and set a width according the first 2 characters (or with a fixed text with 2 characters).

Something like:

val textMeasurer = rememberTextMeasurer()
val textLayoutResult: TextLayoutResult =
    textMeasurer.measure(
        text = AnnotatedString(text.substring(0,2)), //you have to check if the length is <2
        style = LocalTextStyle.current
    )
val textSize = textLayoutResult.size
val density = LocalDensity.current

Text(
    text = text,
    modifier = Modifier
       .width( with(density){textSize.width.toDp()} )
       .background(Yellow), //it is not needed
    maxLines = 1
)
like image 75
Gabriele Mariotti Avatar answered Sep 04 '25 19:09

Gabriele Mariotti