英文:
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
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论