Compose笔记(五十一)--rememberTextMeasurer

这一节主要了解一下Compose中的rememberTextMeasurer,在Jetpack Compose开发中,rememberTextMeasurer是用于测量文本尺寸的工具,它可以帮助我们在不实际绘制文本的情况下,获取文本的宽度、高度、行数等信息。

API

measure(text: AnnotatedString, style: TextStyle, constraints: Constraints):测量文本尺寸,返回TextLayoutResult;

TextLayoutResult:包含文本测量结果,如size(宽高)、lineCount(行数)、getLineEnd()(每行结束索引)等;
场景

文本尺寸预测量:在不渲染文本的情况下获取宽高、行数等信息,为布局决策提供依据

动态布局适配:根据容器大小自动调整文本属性(如字体大小、行数)

交互逻辑支持:实现文本截断、展开 / 收起等依赖文本尺寸的交互功能

栗子:

Kotlin 复制代码
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

@Composable
fun TestDemo() {
    val density = LocalDensity.current
    val textMeasurer = rememberTextMeasurer()
    val containerWidth: Dp = 250.dp 
    val targetText = "使用二分法快速找到适合容器的字体大小......"

   
    val suitableFontSize = remember(targetText, containerWidth, density) {
        val containerWidthPx = with(density) { containerWidth.roundToPx() }
        var minSize = 8.sp    
        var maxSize = 30.sp   
        var bestSize = minSize 

    
        repeat(10) {

            val midSize = ((minSize.value + maxSize.value) / 2).sp 
            val textLayoutResult = textMeasurer.measure(
                text = AnnotatedString(targetText),
                style = TextStyle(fontSize = midSize),
                constraints = Constraints(maxWidth = containerWidthPx)
            )

            if (textLayoutResult.size.width <= containerWidthPx) {            
                bestSize = midSize
                minSize = midSize
            } else {    
                maxSize = midSize
            }
        }
        bestSize
    }

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp)
    ) {
        Text(
            text = targetText,
            style = TextStyle(
                fontSize = suitableFontSize,
                color = Color.Black,
                letterSpacing = 0.5.sp
            ),
            modifier = Modifier.padding(8.dp)
        )
    }
}
Kotlin 复制代码
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.LineBreak
import androidx.compose.ui.unit.Dp

@Composable
fun TextExample() {
    val density = LocalDensity.current
    val textMeasurer = rememberTextMeasurer()
    val maxDisplayLines = 2
    val containerWidth: Dp = 300.dp
    val fullText = "这是一段较长的文本内容,用于演示文本展开和收起功能。" +
            "当文本内容超过指定的最大行数时,会显示「展开」按钮;" +
            "点击后查看全部内容,再次点击则「收起」回到指定行数。"

    val textLayoutResult = remember(fullText, containerWidth, density) {
        val containerWidthPx = with(density) { containerWidth.roundToPx() }

        textMeasurer.measure(
            text = AnnotatedString(fullText),
            style = TextStyle(
                fontSize = 16.sp,
                color = Color.Black,
                lineHeight = 24.sp,
                lineBreak = LineBreak.Paragraph,
            ),
            constraints = Constraints(maxWidth = containerWidthPx)
        )
    }

    val needExpandButton = textLayoutResult.lineCount > maxDisplayLines
    var isExpanded by remember { mutableStateOf(false) }

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp)
    ) {
        Text(
            text = fullText,
            style = TextStyle(
                fontSize = 16.sp,
                color = Color.Black,
                lineHeight = 24.sp
            ),
            maxLines = if (isExpanded) Int.MAX_VALUE else maxDisplayLines,
            overflow = if (needExpandButton && !isExpanded) TextOverflow.Ellipsis else TextOverflow.Visible,
            modifier = Modifier.fillMaxWidth()
        )

        if (needExpandButton) {
            Button(
                onClick = { isExpanded = !isExpanded },
                modifier = Modifier
                    .align(Alignment.BottomEnd)
                    .padding(top = 8.dp)
            ) {
                Text(if (isExpanded) "收起" else "展开")
            }
        }
    }
}

注意

1.避免重复创建TextMeasurer;

2.性能优化:在滚动列表或动画中频繁调用measure()可能导致卡顿,避免频繁测量;

3.TextMeasurer仅测量文本布局,不处理实际渲染或交互;

相关推荐
出门吃三碗饭20 小时前
如何在LLM大语言模型上微调来优化数学推理能力?
android·人工智能·语言模型
shaominjin1231 天前
Android访问OTG文件全解析:从连接到操作的完整指南Android系统访问U盘的实现机制与操作指南
android
骁的小小站1 天前
Verilator 和 GTKwave联合仿真
开发语言·c++·经验分享·笔记·学习·fpga开发
kkkkk0211061 天前
软考高级-系统架构设计师案例专题三:系统开发基础
笔记·系统架构
游戏开发爱好者81 天前
HTTPS 内容抓取实战 能抓到什么、怎么抓、不可解密时如何定位(面向开发与 iOS 真机排查)
android·网络协议·ios·小程序·https·uni-app·iphone
Tom4i1 天前
Android 系统的进程模型
android
介一安全1 天前
【Frida Android】基础篇9:Java层Hook基础——Hook构造函数
android·网络安全·逆向·安全性测试·frida
杨筱毅1 天前
【Android】Compose绘制系统 VS 传统View绘制系统
android
介一安全1 天前
【Frida Android】基础篇10:Native层Hook基础--普通 Hook
android·网络安全·逆向·安全性测试·frida
新子y1 天前
【小白笔记】区分类方法/实例方法和静态函数/命名空间函数
笔记·分类