【HarmonyOS】使用Flex布局和onAreaChange事件计算并记录多行文本位置的实现方案

【HarmonyOS】鸿蒙Flex布局文本位置_鸿蒙

class PosItem {
  x: number
  y: number

  constructor(x: number, y: number) {
    this.x = x
    this.y = y
  }
}

@Entry
@Component
struct Page021 {
  // 原始数据
  @State historyValueArr: Array<string> = ['张三', '李四', '举头望明月', '低头思故乡', 'HarmonyOS', '不可能,绝对不可能', '张三和李四', 'city不city']
  @State result: string[][] | undefined = undefined
  private map: Map<string, PosItem> = new Map<string, PosItem>()

  processPositions(key: string, value: PosItem) {
    this.map.set(key, value)
    if (this.map.size == this.historyValueArr.length) {
      this.convertTo2DArray()
    }
  }

  convertTo2DArray() {
    console.info('创建一个空的对象来存储行数据');
    const rows: ESObject = {};

    this.map.forEach((value, key) => {
      const rowKey = Math.floor(value.y / 26.923076923076923).toString();
      if (!rows[rowKey]) {
        rows[rowKey] = [];
      }
      rows[rowKey].push(key);
    });

    // 对每一行中的元素按x值排序
    Object.keys(rows).forEach(rowKey => {
      rows[rowKey].sort((a: string, b: string) => {
        const posA = this.map.get(a);
        const posB = this.map.get(b);
        return posA!.x - posB!.x;
      });
    });

    this.result = Object.values(rows);
  }

  build() {
    Column() {
      Flex({
        direction: FlexDirection.Row,
        wrap: FlexWrap.Wrap,
      }) {
        ForEach(this.historyValueArr, (item: string, value: number) => {
          Text(item)
            .padding({
              left: '15lpx',
              right: '15lpx',
              top: '7lpx',
              bottom: '7lpx'
            })
            .backgroundColor("#EFEFEF")
            .borderRadius(10)
            .margin('11lpx')
            .onAreaChange((previousArea: Area, currentArea: Area) => {
              console.info(`child currentArea item ${item}`);
              console.info(`child currentArea ${JSON.stringify(currentArea)}`);
              this.processPositions(item, new PosItem(currentArea.position.x as number, currentArea.position.y as number));
            })
        })
      }
      .width('100%')
      .padding({
        left: '26lpx',
        top: '11lpx',
        bottom: '11lpx',
        right: '26lpx'
      })
      .backgroundColor("#F8F8F8")

      ForEach(this.result, (item: Object, index: number) => {
        Text(`第${index}组:${JSON.stringify(item)}`).backgroundColor(Color.Pink)
      })

    }.width('100%')
  }
}