HarmonyOS Text组件如何计算文本行数?

如题:HarmonyOS Text组件如何计算文本行数?

阅读 533
1 个回答

@ohos.measure可以返回多行文字的宽高,没有返回行数,但可以根据业务场景来计算。参考API文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-measure-V5

// 场景一:超过特定行数(下方以3行为例),样式不同,比如加上展开、收缩。 计算文本总高度
let textSize: SizeOptions = measure.measureTextSize({ textContent: this.message, fontSize: 24, constraintWidth: 300 });

// 限定宽度和最大行数(3行),计算高度
let textSize2: SizeOptions = measure.measureTextSize({
  textContent: this.message,
  fontSize: 24,
  maxLines: 3,
  constraintWidth: 300
});
// 若textSize.height > textSize2.height,则表示实际高度超过3行,根据判断结果进行业务处理。
//场景二:组件渲染前预留合适高度展示内容
import measure from '@ohos.measure'

@Entry
@Component
struct Index {
  @State textSize: SizeOptions = { width: 0, height: 0 }
  @State message: string =
    'HarmonyOS NEXT 多设备设计指南与重点特性规范,为您提供面向垂类场景、全端侧的针对性设计建议。 并有简单易用的控件助力您打造高端精致的 HarmonyOS NEXT 应用新体验,与您共同构建一个和谐的数字世界。';

  aboutToAppear(): void {
    this.textSize = measure.measureTextSize({
      textContent: this.message, fontSize: 14, constraintWidth: 300
    })
    console.log(JSON.stringify(this.textSize))
  }

  build() {
    Row() {
      Swiper() {
        Row() {
          Text(this.message)
            .fontSize(14)
            .width(300)
        }
        .backgroundColor(Color.Yellow)
        .width(300)
        .height(px2vp(Number(this.textSize.height)))
      }
    }
    .height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进