HarmonyOS Text获取每行数据宽度

有一段文本在Text中显示 , 显示了多行,那么如何获取每行的文本宽度呢?

其他系统有以下相关方法:

getLayout().getLineEnd(index) //获取指定行的偏移索引
 getLayout().getLineWidth(index)//获取指定行的宽度
HarmonyOS
2025-01-09 15:55:16
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Excelsior_abit

目前HarmonyOS没有直接方法获取,可以参考下这个demo,使用onAreaChange获取高度,使用measure计算每行文本宽度

import measure from '@ohos.measure'

@Entry
@Component
struct Page49 {
  // 预设的默认行高,初始未定义
  private INITIAL_LINE_HEIGHT: number = -1;
  // 状态管理:存储用户输入的文本内容
  @State private textContent: string = '';
  // 状态管理:根据计算显示的行数
  @State private displayedLines: number = 0;

  @State private textWidth: string = '0';
  @State private textHeight: string = '0';
  @State lineIndexArr: number[] = [0];
  @State lineContentArr: string[] = [''];
  @State sliceContent: string = '';

  build() {
    Column() {
      // 按钮以添加字符到文本
      Button('添加文字').onClick(() => {
        this.textContent += '测'+ parseInt(String(Math.random()*1000))+'试'; // 添加一个“测试”至文本内容
      })
      // 按钮以删除最后一个字符
      Button('删除文字').onClick(() => {
        if (this.textContent.length > 0) { // 确保文本非空才执行删除
          this.textContent = this.textContent.slice(0, -1); // 删除最后一个字符
        }
      })
      Button('获取每行文本内容').onClick(()=>{
        this.lineIndexArr = [0];
        this.lineContentArr = [''];
        this.sliceContent = '';
        const count = this.textContent.length;
        const textSize = measure.measureTextSize({
          textContent: this.textContent,
        })
        const textContentWidth = measure.measureText({
          textContent: this.textContent,
        })
        this.sliceContent = this.sliceContent || this.textContent;
        for (let iLine=0;iLine<this.displayedLines;iLine++){
          this.sliceContent = this.sliceContent.slice(this.lineIndexArr[iLine]);
          const content = this.sliceContent;
          console.log(content,'content')
          const currentContentWidth = measure.measureText({
            textContent: content
          });
          if(px2vp(currentContentWidth) < Number(this.textWidth)){
            this.lineContentArr.push(content);
            this.lineIndexArr.push(1);
            break;
          }
          content.split('').forEach((v: string,i:number) => {
            const widthPre = measure.measureText({
              textContent: content.slice(0,i),
            })
            const widthAft = measure.measureText({
              textContent: content.slice(0,i+1),
            })

            if(Number(this.textWidth) > px2vp(widthPre) && Number(this.textWidth) < px2vp(widthAft)){
              const currentContent = content.slice(0,i)
              // this.firstLineContent = currentContent;
              this.lineContentArr.push(currentContent);
              this.lineIndexArr.push(i);
            }
          })
          console.log('this.lineContentArr',this.lineContentArr.toString())
          console.log('this.lineIndexArr',this.lineIndexArr.toString())
        }

      })
      // 显示当前文本行数的提示信息
      Text(`当前行数: ${this.displayedLines}`)
      Text(`文本宽度: ${this.textWidth}`);
      Text(`文本高度: ${this.textHeight}`);
      // 可变高度的文本显示区域,响应式更新行数
      Text(this.textContent)
        .width('50%')// 设置文本宽度为50%
        .onAreaChange((previousArea: Area, currentArea: Area) => {
          // 初始化行高,仅在首次获取到有效高度时设置
          if (this.INITIAL_LINE_HEIGHT == -1 && this.INITIAL_LINE_HEIGHT === this.INITIAL_LINE_HEIGHT && currentArea.height > 0) {
            this.INITIAL_LINE_HEIGHT = currentArea.height as number;
          }
          // 计算并更新显示的行数
          console.log('Previous Height:', previousArea.height);
          console.log('Current Height:', currentArea.height);
          console.log('this.INITIAL_LINE_HEIGHT:', this.INITIAL_LINE_HEIGHT);
          this.displayedLines = Math.ceil(currentArea.height as number / this.INITIAL_LINE_HEIGHT);
          this.textWidth = currentArea.width as string;
        })
      ForEach(this.lineContentArr,(item: string,index: number)=>{
        Text(`第${index}行文本内容:${item}`).fontColor(Color.Green)
      })
    }
    .width('100%')
  }
}
分享
微博
QQ
微信
回复
2025-01-09 17:38:02
相关问题
HarmonyOS Text获取展示的行数
189浏览 • 1回复 待解决
HarmonyOS Text获取文本显示的行数
817浏览 • 1回复 待解决
HarmonyOS Text组件获取当前显示的行数
310浏览 • 1回复 待解决
获取文本Text组件的宽度
844浏览 • 1回复 待解决
如何获取Text组件中文字的宽度
2634浏览 • 1回复 待解决
HarmonyOS Text组件如何计算文本行数
341浏览 • 1回复 待解决
HarmonyOS Text如何设置最大宽度maxWidth
583浏览 • 1回复 待解决
HarmonyOS如何测量Text组件的宽度
658浏览 • 1回复 待解决
HarmonyOS Text内部Span的宽度设置无效
326浏览 • 1回复 待解决