• 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](#gesturetype12)  | 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 a system gesture, that is, a built-in gesture of the component. **true**: The gesture is a system gesture.<br>**false**: The gesture is not a system gesture.<br>Default value: **false**|
47
48## GestureType<sup>12+</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<sup>8+</sup>
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#sourcetype8)| 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<sup>9+</sup> | 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<sup>9+</sup> | 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<sup>9+</sup> | 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<sup>9+</sup> | [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>**Atomic service API**: This API can be used in atomic services since API version 12.|
81| targetDisplayId<sup>15+</sup> | number | ID of the screen where the event occurs.<br>Default value: **0**<br>Value range: [0, +∞).<br>**Atomic service API**: This API can be used in atomic services since API version 15.|
82
83**Error codes**
84
85For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md).
86
87| ID| Error Message|
88| ------- | -------- |
89| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. 2. Parameter verification failed. |
90
91## BaseGestureEvent
92Inherits from [BaseEvent](#baseevent8).
93
94**Atomic service API**: This API can be used in atomic services since API version 12.
95
96| Name     | Type                                     | Description        |
97| ---------  | ----------------------------------------  | -----------|
98| fingerList | [FingerInfo[]](ts-gesture-settings.md#fingerinfo8) | Information about all fingers that trigger the event. |
99
100## TapGestureEvent
101Extended from [BaseGestureEvent](#basegestureevent). This object can be passed in as the **event** parameter of [onGestureJudgeBegin](#ongesturejudgebegin).
102
103**Atomic service API**: This API can be used in atomic services since API version 12.
104
105## LongPressGestureEvent
106Inherits from [BaseGestureEvent](#basegestureevent). This object can be passed in as the **event** parameter of [onGestureJudgeBegin](#ongesturejudgebegin).
107
108**Atomic service API**: This API can be used in atomic services since API version 12.
109
110| Name     | Type                                     | Description        |
111| ---------  | ----------------------------------------  | -----------|
112| repeat     | boolean | Whether the event is repeated. <br>**true**: The event is repeated.<br>**false**: The event is not repeated. |
113
114## PanGestureEvent
115Inherits from [BaseGestureEvent](#basegestureevent). This object can be passed in as the **event** parameter of [onGestureJudgeBegin](#ongesturejudgebegin).
116
117**Atomic service API**: This API can be used in atomic services since API version 12.
118
119| Name     | Type                                     | Description        |
120| ---------  | ----------------------------------------  | -----------|
121| 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. |
122| 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. |
123| 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. |
124| 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.|
125| 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. |
126
127## PinchGestureEvent
128
129**Atomic service API**: This API can be used in atomic services since API version 12.
130
131Inherits from [BaseGestureEvent](#basegestureevent). This object can be passed in as the **event** parameter of [onGestureJudgeBegin](#ongesturejudgebegin).
132| Name        | Type                                     | Description        |
133| ------------  | ----------------------------------------  | -----------|
134| scale         | number | Scale factor. |
135| pinchCenterX  | number | X coordinate of the center of the pinch gesture, in vp, relative to the original area of the current component. |
136| pinchCenterY  | number | Y coordinate of the center of the pinch gesture, in vp, relative to the original area of the current component. |
137
138## RotationGestureEvent
139
140**Atomic service API**: This API can be used in atomic services since API version 12.
141
142Inherits from [BaseGestureEvent](#basegestureevent). This object can be passed in as the **event** parameter of [onGestureJudgeBegin](#ongesturejudgebegin).
143| Name        | Type                                     | Description        |
144| ------------  | ----------------------------------------  | -----------|
145| 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. |
146
147## SwipeGestureEvent
148Inherits from [BaseGestureEvent](#basegestureevent). This object can be passed in as the **event** parameter of [onGestureJudgeBegin](#ongesturejudgebegin).
149
150**Atomic service API**: This API can be used in atomic services since API version 12.
151
152| Name        | Type                                     | Description        |
153| ------------  | ----------------------------------------  | -----------|
154| 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.|
155| 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. |
156## Example
157
158### Example 1: Implementing Custom Gesture Judgment
159
160This example demonstrates how to implement custom judgment for long press, swipe, and pan gestures using **onGestureJudgeBegin**.
161
162```ts
163// xxx.ets
164@Entry
165@Component
166struct Index {
167  @State message: string = '';
168
169  build() {
170    Column() {
171      Row({ space: 20 }) {
172        Text(this.message).width(200).height(80).backgroundColor(Color.Pink)
173          .fontSize(25)
174      }.margin(20)
175    }
176    .width('100%')
177    .height(200)
178    .borderWidth(2)
179    .onDragStart(() => {
180      this.message = 'drag'
181      console.log("Drag start.")
182    })
183    .gesture(
184      TapGesture()
185        .tag("tap1")// Tag for the tap gesture.
186        .onAction(() => {
187          this.message = 'tap1'
188        })
189    )
190    .gesture(
191      LongPressGesture()
192        .tag("longPress1")// Tag for the long press gesture.
193        .onAction(() => {
194          this.message = 'longPress'
195        })
196    )
197    .gesture(
198      SwipeGesture()
199        .tag("swipe1")// Tag for the swipe gesture.
200        .onAction(() => {
201          this.message = 'swipe1'
202        })
203    )
204    .gesture(
205      PanGesture()
206        .tag("pan1")// Tag for the pan gesture.
207        .onActionStart(() => {
208          this.message = 'pan1'
209        })
210    )
211    .onGestureJudgeBegin((gestureInfo: GestureInfo, event: BaseGestureEvent) => {
212      // If the gesture type is a long press gesture, convert the event to a long press gesture event.
213      if (gestureInfo.type == GestureControl.GestureType.LONG_PRESS_GESTURE) {
214        let longPressEvent = event as LongPressGestureEvent;
215        console.log("repeat " + longPressEvent.repeat)
216      }
217      // If the gesture type is a swipe gesture, convert the event to a swipe gesture event.
218      if (gestureInfo.type == GestureControl.GestureType.SWIPE_GESTURE) {
219        let swipeEvent = event as SwipeGestureEvent;
220        console.log("angle " + swipeEvent.angle)
221      }
222      // If the gesture type is a pan gesture, convert the event to a pan gesture event.
223      if (gestureInfo.type == GestureControl.GestureType.PAN_GESTURE) {
224        let panEvent = event as PanGestureEvent;
225        console.log("velocity " + panEvent.velocity)
226      }
227      // Custom criteria
228      if (gestureInfo.type == GestureControl.GestureType.DRAG) {
229        // If REJECT is returned, the drag gesture fails.
230        return GestureJudgeResult.REJECT;
231      } else if (gestureInfo.tag == 'longPress1' && event.fingerList.length > 0 && event.fingerList[0].localY < 100) {
232        // If CONTINUE is returned, the system recognition result is retained.
233        return GestureJudgeResult.CONTINUE;
234      }
235      return GestureJudgeResult.CONTINUE;
236    })
237  }
238}
239```
240![gestures1](figures/gestures1.gif)
241
242### Example 2: Implementing Custom Area Gesture Judgment
243
244This example demonstrates how to use **onGestureJudgeBegin** to determine whether to respond to long press and pan gestures based on the area.
245
246```ts
247// xxx.ets
248import { promptAction } from '@kit.ArkUI';
249
250@Entry
251@Component
252struct Index {
253  scroller: Scroller = new Scroller()
254
255  build() {
256    Scroll(this.scroller) {
257      Column({ space: 8 }) {
258        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')
259          .backgroundColor(0xeeddaa00)
260        Stack({ alignContent: Alignment.Center }) {
261          Column() {
262            // Simulate the upper and lower half areas.
263            Stack().width('200vp').height('100vp').backgroundColor(Color.Red)
264            Stack().width('200vp').height('100vp').backgroundColor(Color.Blue)
265          }.width('200vp').height('200vp')
266          // The lower half area of the stack is an image area bound to the pan gesture.
267          Image($r('sys.media.ohos_app_icon'))
268            .draggable(true)
269            .onDragStart(()=>{
270              promptAction.showToast({ message: "When the blue area is dragged, the image responds" })
271            })
272            .width('200vp').height('200vp')
273          // The upper half area of the stack is a floating area bound to the long press gesture.
274          Stack() {
275          }
276          .width('200vp')
277          .height('200vp')
278          .hitTestBehavior(HitTestMode.Transparent)
279          .onGestureJudgeBegin((gestureInfo: GestureInfo, event: BaseGestureEvent) => {
280            // Check whether the tag has a value.
281            if (gestureInfo.tag) {
282              console.log("gestureInfo tag" + gestureInfo.tag.toString())
283            }
284            console.log("gestureInfo Type " + gestureInfo.type.toString() + " isSystemGesture " + gestureInfo.isSystemGesture);
285            console.log("pressure " + event.pressure + " fingerList.length " + event.fingerList.length
286            + " timeStamp " + event.timestamp + " sourceType " + event.source.toString() + " titleX " + event.tiltX + " titleY " + event.tiltY + " sourcePool " + event.sourceTool.toString());
287            // If the gesture is a long press gesture, check whether the touch position is in the upper half area.
288            if (gestureInfo.type == GestureControl.GestureType.LONG_PRESS_GESTURE) {
289              if (event.fingerList.length > 0 && event.fingerList[0].localY < 100) {
290                return GestureJudgeResult.CONTINUE
291              } else {
292                return GestureJudgeResult.REJECT
293              }
294            }
295            return GestureJudgeResult.CONTINUE
296          })
297          .gesture(GestureGroup(GestureMode.Parallel,
298            LongPressGesture()
299              .onAction((event: GestureEvent) => {
300                promptAction.showToast({ message: "When long pressed, the red area responds." })
301              })
302              .tag("tap111")
303          ))
304
305        }.width('100%')
306      }.width('100%')
307    }
308  }
309}
310```
311![gestures2](figures/gestures2.gif)
312