• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Custom Gesture Judgment
2
3You can use the custom gesture judgment APIs to specify whether to respond to specific gestures when they are being recognized.
4
5>  **NOTE**
6>
7>  This feature is supported since API version 11. Updates will be marked with a superscript to indicate their earliest API version.
8
9
10## onGestureJudgeBegin
11onGestureJudgeBegin(callback: (gestureInfo: GestureInfo, event: BaseGestureEvent) => GestureJudgeResult): T
12
13**Atomic service API**: This API can be used in atomic services since API version 12.
14
15**Parameters**
16| Name       | Type                   | Mandatory | Description                         |
17| ---------- | -------------------------- | ------- | ----------------------------- |
18| callback      | (gestureInfo: [GestureInfo](#gestureinfo), event: [BaseGestureEvent](#basegestureevent)) => [GestureJudgeResult](#gesturejudgeresult11) | Yes    |  Callback for custom gesture judgment. When the gesture bound to the component is accepted, the defined callback is triggered to obtain the result.|
19
20**Return value**
21
22| Type| Description|
23| -------- | -------- |
24| T | Current component.|
25
26
27## GestureJudgeResult<sup>11+</sup>
28
29**Atomic service API**: This API can be used in atomic services since API version 12.
30
31**System capability**: SystemCapability.ArkUI.ArkUI.Full
32
33| Name | Description                                  |
34| ----- | -------------------------------------- |
35| CONTINUE  | The system gesture recognition process continues.|
36| REJECT  | Recognition of the custom gesture is determined as failed.|
37
38## GestureInfo
39
40**Atomic service API**: This API can be used in atomic services since API version 12.
41
42| Name           | Type                       | Description        |
43| ---------------  | -------------------------   | -----------|
44| tag              | string                      | Gesture tag.<br>**NOTE**<br>If the event tag is not set, **undefined** or no gesture tag is returned. |
45| type             | [GestureControl.GestureType](#gesturetype11)  | Gesture type.|
46| isSystemGesture  | boolean                     | Whether the current gesture is system gesture, that is, a built-in gesture of the component.<br>Default value: **false**|
47
48## GestureType<sup>11+</sup>
49
50**Atomic service API**: This API can be used in atomic services since API version 11.
51
52**System capability**: SystemCapability.ArkUI.ArkUI.Full
53
54| Name | Description                                  |
55| ----- | -------------------------------------- |
56| TAP_GESTURE   | Tap gesture.|
57| LONG_PRESS_GESTURE  | Long press gesture.|
58| PAN_GESTURE    | Pan gesture.|
59| PINCH_GESTURE   | Pinch gesture.|
60| SWIPE_GESTURE    | Swipe gesture.|
61| ROTATION_GESTURE   | Rotation gesture.|
62| DRAG    | Drag.|
63| CLICK   | Click.|
64
65## BaseEvent
66
67
68| Name   | Type                                     | Description        |
69| ---------| ----------------------------------------  | -----------|
70| target   | [EventTarget](ts-universal-events-click.md#eventtarget8) | Display area of the element that triggers the gesture event.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 9.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
71| timestamp| number | Timestamp of the event.<br>Unit: ns<br>**Widget capability**: This API can be used in ArkTS widgets since API version 9.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
72| source   | [SourceType](ts-gesture-settings.md#sourcetype)| Event input device.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 9.<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
73| pressure | number | Press pressure.<br>Default value: **0**<br>Value range: [0, 65535). The greater the pressure, the larger the value.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 9.<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
74| tiltX | number | Angle between the projection of the stylus on the device plane and the x-axis.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 9.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
75| tiltY | number | Angle between the projection of the stylus on the device plane and the y-axis.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 9.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
76| sourceTool | [SourceTool](ts-gesture-settings.md#sourcetool9) | Event input source.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 9.<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
77| axisHorizontal<sup>12+</sup> | number | Horizontal axis value.<br>**NOTE**<br>The value can only be obtained in the pan gesture initiated by mouse wheel scrolling or two-finger swipes on a touchpad.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
78| axisVertical<sup>12+</sup> | number | Vertical axis value.<br>**NOTE**<br>The value can only be obtained in the pan gesture initiated by mouse wheel scrolling or two-finger swipes on a touchpad.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
79| getModifierKeyState<sup>12+</sup> | (Array&lt;string&gt;) => bool | Obtains the pressed status of modifier keys. For details about the error message, see the following error codes. The following modifier keys are supported: 'Ctrl'\|'Alt'\|'Shift'\|'Fn'. This API does not work for the Fn key on an externally connected keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
80| deviceId<sup>12+</sup> | number | ID of the input device that triggers the event.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 12.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
81
82**Error codes**
83
84For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md).
85
86| ID| Error Message|
87| ------- | -------- |
88| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. 2. Parameter verification failed. |
89
90## BaseGestureEvent
91Extended from [BaseEvent](#baseevent).
92
93**Atomic service API**: This API can be used in atomic services since API version 12.
94
95| Name     | Type                                     | Description        |
96| ---------  | ----------------------------------------  | -----------|
97| fingerList | [FingerInfo[]](ts-gesture-settings.md#fingerinfo8) | Information about all fingers that trigger the event. |
98
99## TapGestureEvent
100Extended from [BaseGestureEvent](#basegestureevent). This object can be passed in as the **event** parameter of [onGestureJudgeBegin](#ongesturejudgebegin).
101
102**Atomic service API**: This API can be used in atomic services since API version 12.
103
104## LongPressGestureEvent
105Extended from [BaseGestureEvent](#basegestureevent). This object can be passed in as the **event** parameter of [onGestureJudgeBegin](#ongesturejudgebegin).
106
107**Atomic service API**: This API can be used in atomic services since API version 12.
108
109| Name     | Type                                     | Description        |
110| ---------  | ----------------------------------------  | -----------|
111| repeat     | boolean | Whether the event is triggered repeatedly. |
112
113## PanGestureEvent
114Extended from [BaseGestureEvent](#basegestureevent). This object can be passed in as the **event** parameter of [onGestureJudgeBegin](#ongesturejudgebegin).
115
116**Atomic service API**: This API can be used in atomic services since API version 12.
117
118| Name     | Type                                     | Description        |
119| ---------  | ----------------------------------------  | -----------|
120| offsetX    | number | Offset of the gesture event on the x-axis relative to the original area of the current component, in vp. A positive value means to pan from left to right, and a negative value means the opposite. |
121| offsetY    | number | Offset of the gesture event on the y-axis relative to the original area of the current component, in vp. A positive value means to pan from top to bottom, and a negative value means the opposite. |
122| velocityX  | number | Velocity along the x-axis. The origin of the coordinate axis is the upper left corner of the screen. The velocity is positive if the movement is from left to right, and it is negative if the movement is from right to left. The unit is vp/s. |
123| velocityY  | number | Velocity along the y-axis. The origin of the coordinate axis is the upper left corner of the screen. The velocity is positive if the movement is from top to bottom, and it is negative if the movement is from bottom to top. The unit is vp/s.|
124| velocity   | number | Velocity along the main axis. The value is the arithmetic square root of the sum of squares of the velocity along the x- and y-axis. The unit is vp/s. |
125
126## PinchGestureEvent
127
128**Atomic service API**: This API can be used in atomic services since API version 12.
129
130Extended from [BaseGestureEvent](#basegestureevent). This object can be passed in as the **event** parameter of [onGestureJudgeBegin](#ongesturejudgebegin).
131| Name        | Type                                     | Description        |
132| ------------  | ----------------------------------------  | -----------|
133| scale         | number | Scale factor. |
134| pinchCenterX  | number | X coordinate of the center of the pinch gesture, in vp, relative to the original area of the current component. |
135| pinchCenterY  | number | Y coordinate of the center of the pinch gesture, in vp, relative to the original area of the current component. |
136
137## RotationGestureEvent
138
139**Atomic service API**: This API can be used in atomic services since API version 12.
140
141Extended from [BaseGestureEvent](#basegestureevent). This object can be passed in as the **event** parameter of [onGestureJudgeBegin](#ongesturejudgebegin).
142| Name        | Type                                     | Description        |
143| ------------  | ----------------------------------------  | -----------|
144| angle         | number | Rotation angle, in deg.<br>**NOTE**<br>Angle calculation method: After a swipe gesture is recognized, a line connecting the two fingers is identified as the initial line. As the fingers swipe, the line between the fingers rotates. Based on the coordinates of the initial line's and current line's end points, the arc tangent function is used to calculate the respective included angle of the points relative to the horizontal direction by using the following formula: Rotation angle = arctan2(cy2-cy1,cx2-cx1) - arctan2(y2-y1,x2-x1). The initial line is used as the coordinate system. Values from 0 to 180 degrees represent clockwise rotation, while values from –180 to 0 degrees represent counterclockwise rotation. |
145
146## SwipeGestureEvent
147Extended from [BaseGestureEvent](#basegestureevent). This object can be passed in as the **event** parameter of [onGestureJudgeBegin](#ongesturejudgebegin).
148
149**Atomic service API**: This API can be used in atomic services since API version 12.
150
151| Name        | Type                                     | Description        |
152| ------------  | ----------------------------------------  | -----------|
153| angle         | number | Angle of the swipe gesture, that is, the change in the included angle between the line segment created by the two fingers and the horizontal direction. The unit is deg.<br>**NOTE**<br>Angle calculation method: After a swipe gesture is recognized, a line connecting the two fingers is identified as the initial line. As the fingers swipe, the line between the fingers rotates. Based on the coordinates of the initial line's and current line's end points, the arc tangent function is used to calculate the respective included angle of the points relative to the horizontal direction by using the following formula: Rotation angle = arctan2(cy2-cy1,cx2-cx1) - arctan2(y2-y1,x2-x1). The initial line is used as the coordinate system. The clockwise rotation is 0 to 180 degrees, and the counter-clockwise rotation is –180 to 0 degrees.|
154| speed         | number | Swipe gesture speed, that is, the average swipe speed of all fingers relative to the original area of the current component. The unit is vp/s. |
155## Example
156
157### Example 1
158```ts
159// xxx.ets
160@Entry
161@Component
162struct Index {
163  @State message: string = '';
164
165  build() {
166    Column() {
167      Row({ space: 20 }) {
168        Text(this.message).width(200).height(80).backgroundColor(Color.Pink)
169          .fontSize(25)
170      }.margin(20)
171    }
172    .width('100%')
173    .height(200)
174    .borderWidth(2)
175    .onDragStart(() => {
176      this.message = 'drag'
177      console.log("Drag start.")
178    })
179    .gesture(
180      TapGesture()
181        .tag("tap1")// Tag for the tap gesture.
182        .onAction(() => {
183          this.message = 'tap1'
184        })
185    )
186    .gesture(
187      LongPressGesture()
188        .tag("longPress1")// Tag for the long press gesture.
189        .onAction(() => {
190          this.message = 'longPress'
191        })
192    )
193    .gesture(
194      SwipeGesture()
195        .tag("swipe1")// Tag for the swipe gesture.
196        .onAction(() => {
197          this.message = 'swipe1'
198        })
199    )
200    .gesture(
201      PanGesture()
202        .tag("pan1")// Tag for the pan gesture.
203        .onActionStart(() => {
204          this.message = 'pan1'
205        })
206    )
207    .onGestureJudgeBegin((gestureInfo: GestureInfo, event: BaseGestureEvent) => {
208      // If the gesture type is a long press gesture, convert the event to a long press gesture event.
209      if (gestureInfo.type == GestureControl.GestureType.LONG_PRESS_GESTURE) {
210        let longPressEvent = event as LongPressGestureEvent;
211        console.log("repeat " + longPressEvent.repeat)
212      }
213      // If the gesture type is a swipe gesture, convert the event to a swipe gesture event.
214      if (gestureInfo.type == GestureControl.GestureType.SWIPE_GESTURE) {
215        let swipeEvent = event as SwipeGestureEvent;
216        console.log("angle " + swipeEvent.angle)
217      }
218      // If the gesture type is a pan gesture, convert the event to a pan gesture event.
219      if (gestureInfo.type == GestureControl.GestureType.PAN_GESTURE) {
220        let panEvent = event as PanGestureEvent;
221        console.log("velocity " + panEvent.velocity)
222      }
223      // Custom criteria
224      if (gestureInfo.type == GestureControl.GestureType.DRAG) {
225        // If REJECT is returned, the drag gesture fails.
226        return GestureJudgeResult.REJECT;
227      } else if (gestureInfo.tag == 'longPress1' && event.fingerList.length > 0 && event.fingerList[0].localY < 100) {
228        // If CONTINUE is returned, the system recognition result is retained.
229        return GestureJudgeResult.CONTINUE;
230      }
231      return GestureJudgeResult.CONTINUE;
232    })
233  }
234}
235```
236![gestures1](figures/gestures1.gif)
237### Example 2
238```ts
239// xxx.ets
240import { promptAction } from '@kit.ArkUI';
241
242@Entry
243@Component
244struct Index {
245  scroller: Scroller = new Scroller()
246
247  build() {
248    Scroll(this.scroller) {
249      Column({ space: 8 }) {
250        Text("The upper red area is bound to the long press gesture, and the lower blue area is bound to a drag gesture. If a pan is performed after a long press in the upper red area, the area only responds to the long press. In the same case, the lower blue area only responds to the drag.) .width('100%').fontSize(20).fontColor('0xffdd00')
251          .backgroundColor(0xeeddaa00)
252        Stack({ alignContent: Alignment.Center }) {
253          Column() {
254            // Simulate the upper and lower half areas.
255            Stack().width('200vp').height('100vp').backgroundColor(Color.Red)
256            Stack().width('200vp').height('100vp').backgroundColor(Color.Blue)
257          }.width('200vp').height('200vp')
258          // The lower half area of the stack is an image area bound to the pan gesture.
259          Image($r('sys.media.ohos_app_icon'))
260            .draggable(true)
261            .onDragStart(()=>{
262              promptAction.showToast({ message: "When the blue area is dragged, the image responds" })
263            })
264            .width('200vp').height('200vp')
265          // The upper half area of the stack is a floating area bound to the long press gesture.
266          Stack() {
267          }
268          .width('200vp')
269          .height('200vp')
270          .hitTestBehavior(HitTestMode.Transparent)
271          .onGestureJudgeBegin((gestureInfo: GestureInfo, event: BaseGestureEvent) => {
272            // Check whether the tag has a value.
273            if (gestureInfo.tag) {
274              console.log("gestureInfo tag" + gestureInfo.tag.toString())
275            }
276            console.log("gestureInfo Type " + gestureInfo.type.toString() + " isSystemGesture " + gestureInfo.isSystemGesture);
277            console.log("pressure " + event.pressure + " fingerList.length " + event.fingerList.length
278            + " timeStamp " + event.timestamp + " sourceType " + event.source.toString() + " titleX " + event.tiltX + " titleY " + event.tiltY + " sourcePool " + event.sourceTool.toString());
279            // If the gesture is a long press gesture, check whether the touch position is in the upper half area.
280            if (gestureInfo.type == GestureControl.GestureType.LONG_PRESS_GESTURE) {
281              if (event.fingerList.length > 0 && event.fingerList[0].localY < 100) {
282                return GestureJudgeResult.CONTINUE
283              } else {
284                return GestureJudgeResult.REJECT
285              }
286            }
287            return GestureJudgeResult.CONTINUE
288          })
289          .gesture(GestureGroup(GestureMode.Parallel,
290            LongPressGesture()
291              .onAction((event: GestureEvent) => {
292                promptAction.showToast ({ message: "When long pressed, the red area responds." })
293              })
294              .tag("tap111")
295          ))
296
297        }.width('100%')
298      }.width('100%')
299    }
300  }
301}
302```
303![gestures2](figures/gestures2.gif)
304