DEV Community

HarmonyOS
HarmonyOS

Posted on

GestureEvent Coordinate Differences

Read the original article:GestureEvent Coordinate Differences

Requirement Description

When using gesture events, handling different coordinates can produce different movement effects. What are the differences between the coordinates in GestureEvent, and how do you choose the correct one?

Background Knowledge

  • Add Gesture Response: When the user's operation matches the characteristics of a certain gesture, the system recognizes it as that gesture. This process is called gesture recognition. To respond to a specific gesture, a corresponding gesture object must be added to the component so that the system can collect and process it.
  • GestureEvent Object: Inherits from BaseEvent Object and is a data type object used in HarmonyOS to represent gesture events. This object contains the information needed to handle gesture events, such as event type, target information, etc.

Implementation Steps

Main Differences:

The differences between the coordinates involved in a GestureEvent mainly lie in their reference frames. Due to these differences, various coordinates are suitable for different usage scenarios, as shown in the table below:

Coordinate Reference Frame Suitable Usage Scenario
offsetX / offsetY Gesture starting point Calculating sliding distance and direction
localX / localY Top-left corner of the current component’s original area Component internal interaction, such as Canvas drawing
displayX / displayY Top-left corner of the physical screen Global gestures, such as detecting whether a swipe gesture is near the screen edge

Choosing the Right Coordinate Based on Scenario:

Code Snippet

@Entry
@Component
struct EdgeGestureDemo {
  @State edgeTriggered: boolean = false;

  build() {
    Column() {
      Text(this.edgeTriggered ? 'Return gesture triggered' : 'Swipe right from the left edge of the screen')
        .fontSize(20)
        .margin(50)
    }
    .width('100%')
    .height('100%')
    .gesture(
      PanGesture()
        .onActionUpdate((event: GestureEvent) => {
          // Use displayX to detect screen edge
          if (event.fingerList[0].displayX < 60 &&
            event.offsetX > 30) { // Swiped more than 30vp from the edge
            this.edgeTriggered = true;
          }
        })
        .onActionEnd(() => {
          this.edgeTriggered = false;
        })
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

Test Results

cke_958.gif

Limitations or Considerations

This example supports API Version 19 Release and above.

This example supports HarmonyOS 5.1.1 Release SDK and above.

This example must be compiled and run using DevEco Studio 5.1.1 Release and above.

Written by Bunyamin Akcay

Top comments (0)