HarmonyOS Text获取文本显示的行数

需要获取Text的行数,根据行数不同进行不同的布局

HarmonyOS
2024-12-20 17:15:51
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
put_get

@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.
分享
微博
QQ
微信
回复
2024-12-20 19:09:16
相关问题
HarmonyOS Text组件获取当前显示行数
697浏览 • 1回复 待解决
HarmonyOS Text组件如何计算文本行数
741浏览 • 1回复 待解决
HarmonyOS Text获取展示行数
478浏览 • 1回复 待解决
HarmonyOS Text获取行数据宽度
546浏览 • 1回复 待解决
获取文本Text组件宽度
1235浏览 • 1回复 待解决
Text怎么显示带html标签文本
5510浏览 • 1回复 待解决
如何获取文本显示宽度和高度?
1182浏览 • 1回复 待解决
ArkTS实现Text文本【...展开】
2556浏览 • 3回复 待解决
HarmonyOS Text文本描边实现
777浏览 • 1回复 待解决
Text怎么设置文本渐变?
1230浏览 • 0回复 待解决
HarmonyOS Text显示异常
500浏览 • 1回复 待解决