Text中的ImageSpan支持onAreaChange事件,可通过在Span前添加一个宽高均为0的ImageSpan,在ImageSpan的onAreaChange获取到ImageSpan的位置,即为Span的位置。
@Entry @Component struct SpanPage { @State span2x: number = 0; @State span2y: number = 0; build() { Column() { Text() { Span('Span1') .fontSize(18); ImageSpan($r('app.media.startIcon')) .width(0) .height(0) .border({ width: 1 }) .onAreaChange((oldValue: Area, newValue: Area) => { this.span2x = newValue.globalPosition.x as number; this.span2y = newValue.globalPosition.y as number; console.info(`Span2相对页面左上角的x坐标为${newValue.globalPosition.x},y坐标为${newValue.globalPosition.y}`); }); Span('Span2') .fontSize(18); }; Text(`Span2相对页面左上角的x坐标为${this.span2x},y坐标为${this.span2y}`); } .height('100%') .width('100%'); } }