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.<br>**NOTE**<br> When the gesture is a built-in gesture event of an unexposed type, the value of **type** is **-1**.|
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 | Value| Description                                  |
55| ----- | -------- | -------------------------------------- |
56| TAP_GESTURE   | 0 | Tap gesture.|
57| LONG_PRESS_GESTURE  | 1 | Long press gesture.|
58| PAN_GESTURE    | 2 | Pan gesture.|
59| PINCH_GESTURE   | 3 | Pinch gesture.|
60| SWIPE_GESTURE    | 4 | Swipe gesture.|
61| ROTATION_GESTURE   | 5 | Rotation gesture.|
62| DRAG    | 6 | Drag.|
63| CLICK   | 7 | 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. It is the interval between the time when the event is triggered and the time when the system starts.<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, 1], typical value 0.913168, where higher values indicate greater pressure.<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: Implementing Custom Gesture Judgment
158
159This example demonstrates how to implement custom judgment for long press, swipe, and pan gestures using **onGestureJudgeBegin**.
160
161```ts
162// xxx.ets
163@Entry
164@Component
165struct Index {
166  @State message: string = '';
167
168  build() {
169    Column() {
170      Row({ space: 20 }) {
171        Text(this.message).width(200).height(80).backgroundColor(Color.Pink)
172          .fontSize(25)
173      }.margin(20)
174    }
175    .width('100%')
176    .height(200)
177    .borderWidth(2)
178    .onDragStart(() => {
179      this.message = 'drag'
180      console.log("Drag start.")
181    })
182    .gesture(
183      TapGesture()
184        .tag("tap1")// Tag for the tap gesture.
185        .onAction(() => {
186          this.message = 'tap1'
187        })
188    )
189    .gesture(
190      LongPressGesture()
191        .tag("longPress1")// Tag for the long press gesture.
192        .onAction(() => {
193          this.message = 'longPress'
194        })
195    )
196    .gesture(
197      SwipeGesture()
198        .tag("swipe1")// Tag for the swipe gesture.
199        .onAction(() => {
200          this.message = 'swipe1'
201        })
202    )
203    .gesture(
204      PanGesture()
205        .tag("pan1")// Tag for the pan gesture.
206        .onActionStart(() => {
207          this.message = 'pan1'
208        })
209    )
210    .onGestureJudgeBegin((gestureInfo: GestureInfo, event: BaseGestureEvent) => {
211      // If the gesture type is a long press gesture, convert the event to a long press gesture event.
212      if (gestureInfo.type == GestureControl.GestureType.LONG_PRESS_GESTURE) {
213        let longPressEvent = event as LongPressGestureEvent;
214        console.log("repeat " + longPressEvent.repeat)
215      }
216      // If the gesture type is a swipe gesture, convert the event to a swipe gesture event.
217      if (gestureInfo.type == GestureControl.GestureType.SWIPE_GESTURE) {
218        let swipeEvent = event as SwipeGestureEvent;
219        console.log("angle " + swipeEvent.angle)
220      }
221      // If the gesture type is a pan gesture, convert the event to a pan gesture event.
222      if (gestureInfo.type == GestureControl.GestureType.PAN_GESTURE) {
223        let panEvent = event as PanGestureEvent;
224        console.log("velocity " + panEvent.velocity)
225      }
226      // Custom criteria
227      if (gestureInfo.type == GestureControl.GestureType.DRAG) {
228        // If REJECT is returned, the drag gesture fails.
229        return GestureJudgeResult.REJECT;
230      } else if (gestureInfo.tag == 'longPress1' && event.fingerList.length > 0 && event.fingerList[0].localY < 100) {
231        // If CONTINUE is returned, the system recognition result is retained.
232        return GestureJudgeResult.CONTINUE;
233      }
234      return GestureJudgeResult.CONTINUE;
235    })
236  }
237}
238```
239![gestures1](figures/gestures1.gif)
240
241### Example 2: Implementing Custom Area Gesture Judgment
242
243This example demonstrates how to use **onGestureJudgeBegin** to determine whether to respond to long press and pan gestures based on the area.
244
245```ts
246// xxx.ets
247import { promptAction } from '@kit.ArkUI';
248
249@Entry
250@Component
251struct Index {
252  scroller: Scroller = new Scroller()
253
254  build() {
255    Scroll(this.scroller) {
256      Column({ space: 8 }) {
257        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')
258          .backgroundColor(0xeeddaa00)
259        Stack({ alignContent: Alignment.Center }) {
260          Column() {
261            // Simulate the upper and lower half areas.
262            Stack().width('200vp').height('100vp').backgroundColor(Color.Red)
263            Stack().width('200vp').height('100vp').backgroundColor(Color.Blue)
264          }.width('200vp').height('200vp')
265          // The lower half area of the stack is an image area bound to the pan gesture.
266          Image($r('sys.media.ohos_app_icon'))
267            .draggable(true)
268            .onDragStart(()=>{
269              promptAction.showToast({ message: "When the blue area is dragged, the image responds" })
270            })
271            .width('200vp').height('200vp')
272          // The upper half area of the stack is a floating area bound to the long press gesture.
273          Stack() {
274          }
275          .width('200vp')
276          .height('200vp')
277          .hitTestBehavior(HitTestMode.Transparent)
278          .onGestureJudgeBegin((gestureInfo: GestureInfo, event: BaseGestureEvent) => {
279            // Check whether the tag has a value.
280            if (gestureInfo.tag) {
281              console.log("gestureInfo tag" + gestureInfo.tag.toString())
282            }
283            console.log("gestureInfo Type " + gestureInfo.type.toString() + " isSystemGesture " + gestureInfo.isSystemGesture);
284            console.log("pressure " + event.pressure + " fingerList.length " + event.fingerList.length
285            + " timeStamp " + event.timestamp + " sourceType " + event.source.toString() + " titleX " + event.tiltX + " titleY " + event.tiltY + " sourcePool " + event.sourceTool.toString());
286            // If the gesture is a long press gesture, check whether the touch position is in the upper half area.
287            if (gestureInfo.type == GestureControl.GestureType.LONG_PRESS_GESTURE) {
288              if (event.fingerList.length > 0 && event.fingerList[0].localY < 100) {
289                return GestureJudgeResult.CONTINUE
290              } else {
291                return GestureJudgeResult.REJECT
292              }
293            }
294            return GestureJudgeResult.CONTINUE
295          })
296          .gesture(GestureGroup(GestureMode.Parallel,
297            LongPressGesture()
298              .onAction((event: GestureEvent) => {
299                promptAction.showToast({ message: "When long pressed, the red area responds." })
300              })
301              .tag("tap111")
302          ))
303
304        }.width('100%')
305      }.width('100%')
306    }
307  }
308}
309```
310![gestures2](figures/gestures2.gif)
311