#鸿蒙通关秘籍#怎样在触摸事件中获取按压类型及位置

HarmonyOS
2024-12-05 13:52:30
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
SKU流星赶月

要获取触摸事件中的按压类型及其坐标,可以使用onTouch回调函数,通过判断event.type获取触摸类型,并通过event.touches获取坐标如下示例:

@Entry
@Component
struct TouchExample {
  @State text: string = '';
  @State eventType: string = '';

  build() {
    Column() {
      Button('Touch').height(40).width(100)
        .onTouch((event?: TouchEvent) => {
          if(event){
            switch (event.type) {
              case TouchType.Down:
                this.eventType = 'Down';
                break;
              case TouchType.Up:
                this.eventType = 'Up';
                break;
              case TouchType.Move:
                this.eventType = 'Move';
                break;
            }
            this.text = `TouchType: ${this.eventType}\nPosition: x: ${event.touches[0].x}, y: ${event.touches[0].y}`;
          }
        })
      Text(this.text)
    }.width('100%').padding(30)
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.

这样可以显示并更新触摸事件类型和触碰位置坐标。

分享
微博
QQ
微信
回复
2024-12-05 16:15:35
相关问题
鸿蒙响应屏幕触摸事件如何获取
8304浏览 • 1回复 已解决