文档开发者中心
我的
|

ArkUI (方舟UI框架)

UI

HarmonyOS 5

HarmonyOS 一个Text组件 在渲染出来之前,能否提前知道他的文案展示的实际高度是多少? (API12+)

HarmonyOS 一个Text组件 在渲染出来之前,能否提前知道他的文案展示的实际高度是多少? (API12+)

点赞
收藏
回复
1
分享
举报
浏览43 发布于2026-04-02 11:25未知归属地
全部评论
最多点赞
最新发布
最早发布
  1. 通过MeasureText.measureTextSize()计算文本的宽高。
  2. 通过Math.floor()向下取整,获取文本行数。
  3. 设置textOverflow属性使文本始终显示完整文本,超出部分用省略号表示。

示例代码如下:

收起
自动换行
深色代码主题
复制
import { MeasureText } from '@kit.ArkUI'

@Entry
@Component
struct Index {
  @State message: string = 'HarmonyOS HarmonyOS HarmonyOS'
  @State Line: number = 1
  @State textSizeWidth: number = 0
  @State textSizeHeight: number = 0

  aboutToAppear(): void {
    let textSize: SizeOptions = MeasureText.measureTextSize({
      textContent: this.message,
      fontSize: 20
    })
    this.textSizeWidth = textSize.width as number
    this.textSizeHeight = textSize.height as number
  }

  build() {
    Row() {
      Column() {
        Text(`文本宽度: ${this.textSizeWidth},文本高度:${this.textSizeHeight}`)
        Text(`${this.message}`)
          .width('200')
          .maxLines(this.Line)
          .textOverflow({ overflow: TextOverflow.Ellipsis })
          .width('200')
        Button('修改文本内容')
          .onClick(() => {
            this.message =
              'developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-measure-V5#measureoptions'
            let textSize: SizeOptions = MeasureText.measureTextSize({
              textContent: this.message,
              fontSize: 25
            })
            this.textSizeWidth = textSize.width as number
            this.textSizeHeight = textSize.height as number
            let lineHeight = px2vp(Number(textSize.height))
            let textHeight = 60
            this.Line = Math.floor(textHeight / lineHeight)
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

ComponentContent封装的WrappedBuilder对象,这个WrappedBuilder对象是一个全局@Builder,可以给它的根组件添加onAppear回调函数,来执行获取text文本高度的代码。

展开全部
1楼回复于2026-04-02 11:25 未知归属地
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要提问题

了解社区公约,与您携手共创和谐专业的开发者社区。