Jetpack Compose 中的 android:autoSizeTextType [英] android:autoSizeTextType in Jetpack Compose

查看:96
本文介绍了Jetpack Compose 中的 android:autoSizeTextType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法调整文本以始终根据固定高度调整大小?

Is there a way to adjust the text to always resize depending a fixed height ?

我有一列高度固定,里面的文字总是适合

I have a column that has a fixed height and in which the text inside should always fit

 Column(modifier = Modifier.height(150.dp).padding(8.dp)) {
   Text("My really long long long long long text that needs to be resized to the height of this Column")
}

推荐答案

我使用以下内容根据可用宽度调整字体大小:

I use the following to adjust the font size with respect to the available width:

val textStyleBody1 = MaterialTheme.typography.body1
var textStyle by remember { mutableStateOf(textStyleBody1) }
var readyToDraw by remember { mutableStateOf(false) }
Text(
    text = "long text goes here",
    style = textStyle,
    maxLines = 1,
    softWrap = false,
    modifier = modifier.drawWithContent {
        if (readyToDraw) drawContent()
    },
    onTextLayout = { textLayoutResult ->
        if (textLayoutResult.didOverflowWidth) {
            textStyle = textStyle.copy(fontSize = textStyle.fontSize * 0.9)
        } else {
            readyToDraw = true
        }
    }
)

要根据高度调整字体大小,请使用 Text 组合属性并使用 didOverflowHeight 而不是 didOverflowWidth:

To adjust the font size based on height, play around with the Text composable's attributes and use didOverflowHeight instead of didOverflowWidth:

val textStyleBody1 = MaterialTheme.typography.body1
var textStyle by remember { mutableStateOf(textStyleBody1) }
var readyToDraw by remember { mutableStateOf(false) }
Text(
    text = "long text goes here",
    style = textStyle,
    overflow = TextOverflow.Clip,
    modifier = modifier.drawWithContent {
        if (readyToDraw) drawContent()
    },
    onTextLayout = { textLayoutResult ->
        if (textLayoutResult.didOverflowHeight) {
            textStyle = textStyle.copy(fontSize = textStyle.fontSize * 0.9)
        } else {
            readyToDraw = true
        }
    }
)

如果您需要在列表中的多个项目之间同步字体大小,请将文本样式保存在可组合函数之外:

In case you need to synchronize the font size across multiple items in a list, save the text style outside of the composable function:

private val textStyle = mutableStateOf(MaterialTheme.typography.body1)

@Composable
fun YourComposable() {
    Text(...)
}

这当然不是完美的,因为它可能需要一些帧,直到大小合适并最终绘制文本.

This is certainly not perfect, as it might take some frames until the size fits and the text draws finally.

这篇关于Jetpack Compose 中的 android:autoSizeTextType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆