在研发过程中,因为组件之间的布局关系,需要基于某个组件的坐标信息计算出另外组件的坐标信息的情况。

常用的方式分为两种,一种是使用getRectangleById获取的方式,一种是监听组件的onAreaChange事件获取的方式。

本篇的内容介绍调用getRectangleById方法获取的方式,这种方式获取的坐标信息的单位为px,通常适用于有具体的事件触发时调用,并获取组件的坐标信息。

下面的例子,当Button点击后,Text的坐标跟随变动

@Entry
@Component
struct Index {
  @State buttonX:number = 0;
  @State buttonY:number = 0;
  build() {
    Column({ space: 18 }) {
      Button('Click Me')
        .id('myButton') // 必须设置唯一ID
        .onClick(() => {
          const componentInfo = this.getUIContext().getComponentUtils().getRectangleById('myButton');
          this.buttonX = Math.round(px2vp(componentInfo.screenOffset.x)); // px to pv
          this.buttonY = Math.round(px2vp(componentInfo.screenOffset.y)); // px to pv
        })
      // Button点击后,更改位置
      Text('Popup Content')
        .position({ x: this.buttonX, y: this.buttonY + 50 }) // Y坐标下方偏移
    }.width('100%').height("100%").padding({ top: 5 })
  }
}