在研发过程中,因为组件之间的布局关系,需要基于某个组件的坐标信息计算出另外组件的坐标信息的情况。
常用的方式分为两种,一种是使用getRectangleById获取的方式,一种是监听组件的onAreaChange事件获取的方式。
本篇的内容介绍使用onAreaChange获取的方式,这种方式获取的坐标信息的单位为vp。在组件布局完成后坐标就可获取。
@Entry
@Component
struct Index {
@State buttonX:number = 0;
@State buttonY:number = 0;
build() {
Column({ space: 18 }) {
Text()
.height(88)
Button('Follow Me')
.onAreaChange((oldValue: Area, newValue: Area) => {
this.buttonX = newValue.position.x as number;
this.buttonY = newValue.position.y as number;
})
// 左对齐,跟随Button
Text('Popup Content')
.position({ x: this.buttonX, y: this.buttonX + 50 }) // Y坐标下方偏移
}
.width('100%').height("100%").padding({ top: 5 })
}
}
















