【HarmonyOS】Flex布局文本位置
【HarmonyOS】使用Flex布局和onAreaChange事件计算并记录多行文本位置的实现方案
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%') } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了