You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jetpack Compose中实现尺寸布局正确的竖向文本显示

问题根源

rotate 修饰符属于绘制阶段修饰符,仅会改变内容的绘制角度,不会参与组件的测量、布局计算流程,所以旋转后的组件布局尺寸仍然是文本横向展示时的宽高,自然会在横向占用多余空间,不符合竖向文本窄宽度的需求。

实现方案

通过自定义LayoutModifier拦截测量、布局流程,主动交换90度旋转后的组件宽高,同时自动适配文本内容长度、字体大小、行高变化,无需硬编码固定尺寸。

第一步:自定义竖向旋转修饰符

fun Modifier.rotateVertically(rotation: Float = -90f) = this.then(
    // 先调整布局测量、摆放逻辑,修正组件尺寸
    layout { measurable, constraints ->
        val placeable = measurable.measure(constraints)
        // 90/270度旋转后宽高互换
        layout(placeable.height, placeable.width) {
            when (rotation) {
                -90f -> placeable.place(x = -placeable.width, y = 0)
                90f -> placeable.place(x = 0, y = -placeable.height)
                else -> placeable.place(0, 0)
            }
        }
    }
)
// 最后添加旋转修饰符处理绘制角度
.then(rotate(rotation))

第二步:替换原有rotate修饰符

将你示例代码中Text的rotate(-90f)替换为上面的rotateVertically(-90f)即可:

Text(
    modifier = Modifier
        .padding(4.dp)
        .background(Color.Gray)
        .rotateVertically(-90f), // 替换原有rotate方法
    text = "This should be vertical text on the left side"
)
特性说明
  • 布局层面直接修正了组件的宽高,水平方向占用宽度等于原文本的行高,完全适配系统字体大小、行高设置变更
  • 文本内容长度变化时,组件高度(原文本宽度)会自动适配,不会出现内容截断
  • 背景、padding等修饰符放在rotateVertically前即可跟随文本一起旋转,显示效果符合预期

内容的提问来源于stack exchange,提问作者Tyler V

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 22:36:03