HarmonyOS 如何在长图展示时加入滑动手势(滑动后手指离开屏幕显示内容仍能滑动一小段距离,且在这个过程中能通过拖动终止自己滑动这个过程转为手指拖动,也能通过长按打断图片自己滑动的过程)?

HarmonyOS 提供了滑动手势(SwipeGesture),手势触发后可以获取速度和角度参数,如何利用这两个参数实现滑动展示图片且能通过其他手势中断滑动过程,滑动后手指离开屏幕显示内容仍能滑动一小段距离,且在这个过程中能通过拖动终止自己滑动这个过程转为手指拖动,也能通过长按打断图片自己滑动的过程

阅读 644
1 个回答

可以在PanGesture.onActionEnd根据velocityX和velocityY使用animateTo函数实现惯性滑动的效果。 可以参考下如下demo:

@Entry 
@Component 
struct Index { 
  @State offsetX: number = 0 
  @State offsetY: number = 0 
  @State positionX: number = 0 
  @State positionY: number = 0 
  private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.All }) 
  @State vX: number = 0 
  @State vY: number = 0 
 
  build() { 
    Column() { 
      Text('PanGesture offset:\nX: ' + this.offsetX + '\n' + 'Y: ' + this.offsetY) 
      Text('PanGesture speed:\nVX: ' + this.vX + '\n' + 'VY: ' + this.vY) 
    } 
    .height(150) 
    .width(300) 
    .padding(20) 
    .border({ width: 3 }) 
    .margin(50) 
    .translate({ x: this.offsetX, y: this.offsetY, z: 0 }) // 以组件左上角为坐标原点进行移动 
    .gesture( 
      PanGesture(this.panOption) 
        .onActionStart((event?: GestureEvent) => { 
          console.info('Pan start') 
        }) 
        .onActionUpdate((event: GestureEvent) => { 
          animateTo({ 
            duration: 0, 
            curve: Curve.EaseOut, 
            iterations: 1, 
            playMode: PlayMode.Normal, 
          }, () => { 
          }) 
          if (event) { 
            this.offsetX = this.positionX + event.offsetX 
            this.offsetY = this.positionY + event.offsetY 
            console.info('Pan Update') 
          } 
        }) 
        .onActionEnd((event: GestureEvent) => { 
          this.vX = event.velocityX 
          this.vY = event.velocityY 
          if (Math.abs(this.vX) < 50 && Math.abs(this.vY) < 50) { 
            this.positionX = this.offsetX 
            this.positionY = this.offsetY 
            return 
          } 
          animateTo({ 
            duration: 1000, 
            curve: Curve.EaseOut, 
            iterations: 1, 
            playMode: PlayMode.Normal, 
          }, () => { 
            this.offsetX = this.positionX + this.vX / 2 
            this.offsetY = this.positionY + this.vY / 2 
            this.positionX = this.offsetX 
            this.positionY = this.offsetY 
          }) 
          console.info('Pan end') 
        }) 
    ) 
  } 
}

目前的规格中没有惯性滑动的接口实现,可以参考以下demo看能否满足诉求:

https://gitee.com/yeyinglong/ark-uicomponent-sample/blob/master/CircularScroll/CircularScroll.ets

https://gitee.com/yeyinglong/ark-uicomponent-sample/blob/master/InfiniteScroll/InfiniteScroll.ets

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进