HarmonyOS 计算多行文本布局宽高?

以下只支持计算单行文本宽高, 有支持多行的么? 或其它解决方案

import measure from '@ohos.measure'

measure.measureTextSize10+
measureTextSize(options: MeasureOptions): SizeOptions

计算指定文本单行布局下的宽度和高度

阅读 483
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 = '很长很长的一段很长很长的一段很长很长的一段很长很长的一段很长很长的一段很长很长的一段很长很长的一段很长很长的一段很长很长的一段很长很长的一段很长很长的一段很长很长的一段很长很长的一段很长很长的一段很长很长的一段很长很长的一段';
  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%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进