HarmonyOS 计算多行文本布局宽高

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

import measure from '@ohos.measure'

measure.measureTextSize10+
measureTextSize(options: MeasureOptions): SizeOptions
  • 1.
  • 2.
  • 3.
  • 4.

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

HarmonyOS
2024-12-24 15:34:00
794浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
zbw_apple

@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%')
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
分享
微博
QQ
微信
回复
2024-12-24 17:51:07
相关问题
HarmonyOS 计算文本的实现方案
942浏览 • 1回复 待解决
HarmonyOS 多行文本中间省略不生效
564浏览 • 1回复 待解决
HarmonyOS Text多行文本不能居中对齐
1886浏览 • 1回复 待解决
多行文本省略的展开与显示
1914浏览 • 1回复 待解决
多行文字后面添加标签
794浏览 • 1回复 待解决
HarmonyOS 文本计算不准
1000浏览 • 1回复 待解决
HarmonyOS RelativeContainer设置问题
520浏览 • 1回复 待解决
HarmonyOS 获取图片的
901浏览 • 1回复 待解决
HarmonyOS ArkUI中设置
700浏览 • 1回复 待解决
HarmonyOS richtext如何控制
617浏览 • 1回复 待解决
HarmonyOS RelativeContainer 不能自适应
1060浏览 • 1回复 待解决
HarmonyOS RelativeContainer自适应问题
1688浏览 • 1回复 待解决