DEV Community

HarmonyOS
HarmonyOS

Posted on

Swipe Speed Detection Using onTouch in ArkTS

Read the original article:Swipe Speed Detection Using onTouch in ArkTS

Requirement Description

Implement a feature that tracks the speed of the finger swipe on the screen using the onTouch event in an ArkTS-based HarmonyOS application.

Background Knowledge

  • HarmonyOS's onTouch event captures TouchType.Down, TouchType.Move, and TouchType.Up interactions.
  • By recording the timestamp and position on TouchType.Down and updating during TouchType.Move, we can calculate velocity as:

cke_6316.png

Implementation Steps
  1. On TouchType.Down, record the start time and coordinates.
  2. On TouchType.Move, calculate the distance moved and time difference.
  3. Derive the velocity in x, y, and combined vector form.
Code

@Entry
@Component
struct TouchSpeedExample {
  @State lastX: number = 0
  @State lastY: number = 0
  @State lastTime: number = 0
  @State velocityX: number = 0
  @State velocityY: number = 0
  @State velocity: number = 0

  build() {
    Column() {
      Text(`Speed X: ${this.velocityX.toFixed(3)} px/ms`)
      Text(`Speed Y: ${this.velocityY.toFixed(3)} px/ms`)
      Text(`Total Speed: ${this.velocity.toFixed(3)} px/ms`)
      Text('Swipe area below:')
      Column()
        .height(500)
        .width('100%')
        .backgroundColor(Color.Grey)
        .onTouch((event: TouchEvent) => {
          const now = new Date().getTime()
          if (event.type === TouchType.Down) {
            this.lastX = event.touches[0].x
            this.lastY = event.touches[0].y
            this.lastTime = now
          } else if (event.type === TouchType.Move) {
            const deltaTime = now - this.lastTime
            const deltaX = event.touches[0].x - this.lastX
            const deltaY = event.touches[0].y - this.lastY
            if (deltaTime > 0) {
              this.velocityX = Math.abs(deltaX / deltaTime)
              this.velocityY = Math.abs(deltaY / deltaTime)
              this.velocity = Math.sqrt(this.velocityX ** 2 + this.velocityY ** 2)
            }
            this.lastX = event.touches[0].x
            this.lastY = event.touches[0].y
            this.lastTime = now
          }
        })
    }.padding(20)
  }
}
Enter fullscreen mode Exit fullscreen mode
Test Results
  • Works as expected on API 16 using DevEco Studio 5.0.4 on both real devices (e.g., Mate 60) and emulator.
  • Detects swipe speeds and updates in real time.
Limitations
  • Time resolution limited by Date.getTime() (millisecond precision).
  • High-frequency swipes may need filtering or smoothing.
  • Ensure onTouch area is large enough to capture gestures properly.

Written by Taha Enes Kon

Top comments (0)