文本组合 – 字符宽度

huangapple go评论68阅读模式
英文:

Compose Text - width in chars

问题

有没有办法告诉Text组合在任何提供的文本下都能宽度为例如2个字符?

我想要一行,其中包括权重和一些固定大小的单元格,但是我希望这些固定大小的单元格的宽度正好足够容纳提供的字体的n个字符…

英文:

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...

答案1

得分: 1

你可以使用 `TextMeasurer` 来测量文本并根据前两个字符的宽度设置宽度或者使用固定的两个字符的文本)。

类似于

```kotlin
val textMeasurer = rememberTextMeasurer()
val textLayoutResult: TextLayoutResult =
    textMeasurer.measure(
        text = AnnotatedString(text.substring(0,2)), //你需要检查长度是否小于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), //这部分不是必需的
    maxLines = 1
)
英文:

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
)

huangapple
  • 本文由 发表于 2023年3月9日 19:48:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75684189.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定