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
onTouchevent capturesTouchType.Down,TouchType.Move, andTouchType.Upinteractions. - By recording the timestamp and position on
TouchType.Downand updating duringTouchType.Move, we can calculate velocity as:
Implementation Steps
- On
TouchType.Down, record the start time and coordinates. - On
TouchType.Move, calculate the distance moved and time difference. - 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)
}
}
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
onToucharea is large enough to capture gestures properly.

Top comments (0)