PanGesture实现控件拖动的效果,通过拖动的坐标位置调用position或者translate方法来更新UI的位置。效果见下图:

 具体代码如下:
// xxx.ets
struct PanGestureExample {
   offsetX: number = 0
   offsetY: number = 0
  positionX: number = 0
  positionY: number = 0
  private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.All })
  build() {
    Column() {
      Column() {
        Text('PanGesture offset:\nX: ' + this.offsetX + '\n' + 'Y: ' + this.offsetY)
      }
      .height(200)
      .width(300)
      .padding(20)
      .border({ width: 3 })
      .margin(50)
      .onClick(()=>{
        console.info('Pan click')
      })
      .translate({ x: this.offsetX, y: this.offsetY }) // 以组件左上角为坐标原点进行移动,此处也可以调用position({ x: this.offsetX, y: this.offsetY }) 方法
      // 左右拖动触发该手势事件
      .gesture(
        PanGesture(this.panOption)
          .onActionStart((event: GestureEvent) => {
            console.info('Pan start')
          })
          .onActionUpdate((event: GestureEvent) => {
            if (event) {
              this.offsetX = this.positionX + event.offsetX
              this.offsetY = this.positionY + event.offsetY
            }
          })
          .onActionEnd((event: GestureEvent) => {
            //记录拖动结束前停留的位置
            this.positionX = this.offsetX
            this.positionY = this.offsetY
            console.info('Pan end')
          })
      )
    }
  }
}
通过这个PanGesture,可以实现更复杂的功能,比如ListView的item排序等,后面会写相关博文出来。
 参考资料:
 HarmonyOS(40) 悬浮框实现
 PanGesture


















![[IMX6ULL]移植NXP Linux Kernel 5.15](https://i-blog.csdnimg.cn/direct/7b84efcb7e5e439ea9e71547c8ecb312.png)
