HarmonyOS 计算文字高度?

1、使用measure.measureTextSize计算文字在规定宽度下显示的高度,计算的值不准确,比预期大很多。

let tipsSize:SizeOptions = measure.measureTextSize({
  textContent: this.otpKeyBoardTips,
  fontSize: 16,
  constraintWidth: YTDeviceUtil.getDeviceWidth() - 40
});
let tipsHeight = tipsSize.height as number;

2、measure.measureTextSize方法返回的宽高都是是Length类型。可以直接用 as number转换吗

阅读 592
1 个回答

1、在使用该api时,需要特别注意MeasureOptions的设置,尤其是单位大小的统一

参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-measure-V5\#measureoptions

demo:

import measure from '@ohos.measure'

@Entry
@Component
struct Index {

  textSize: SizeOptions = measure.measureTextSize({
    textContent: "Hello word",
    fontSize: '16px'
  })
  textSize1: SizeOptions = measure.measureTextSize({
    textContent: "Hello word",
    fontSize: `${fp2px(16)}`+'px'
  });

  build() {
    Row() {
      Column() {
        Text(`The width of 'Hello World': ${this.textSize.width as number}`)
        Text(`The width of 'Hello World': ${this.textSize1.width}`)
        Text(`The height of 'Hello World': ${this.textSize.height as number}`)
        Text(`The height of 'Hello World': ${this.textSize1.height}`)
      }
      .width('100%')
    }
    .height('100%')
  }
}

2、measure.measureTextSize方法返回的宽高都是是Length类型。可以直接用 as number转换吗

–可以

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进