• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# XComponent
2<!--Kit: ArkUI-->
3<!--Subsystem: ArkUI-->
4<!--Owner: @zjsxstar-->
5<!--Designer: @sunbees-->
6<!--Tester: @liuli0427-->
7<!--Adviser: @HelloCrease-->
8
9提供用于图形绘制和媒体数据写入的[Surface](../../../ui/napi-xcomponent-guidelines.md#概述),XComponent负责将其嵌入到视图中,支持应用自定义Surface位置和大小。具体指南请参考[自定义渲染 (XComponent)文档](../../../ui/napi-xcomponent-guidelines.md)。
10
11> **说明:**
12>
13> 该组件从API version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
14
15
16## 子组件
1718
19## 接口
20
21### XComponent<sup>19+</sup>
22
23XComponent(params: NativeXComponentParameters)
24
25在Native侧获取XComponent节点实例、注册XComponent持有的Surface的生命周期回调和触摸、鼠标、按键等组件事件回调。
26
27**原子化服务API:** 从API version 19开始,该接口支持在原子化服务中使用。
28
29**系统能力:** SystemCapability.ArkUI.ArkUI.Full
30
31**参数:**
32
33| 参数名  | 类型                                | 必填 | 说明                           |
34| ------- | --------------------------------------- | ---- | ------------------------------ |
35| params | [NativeXComponentParameters](#nativexcomponentparameters19) | 是   | 定义XComponent的具体配置参数。 |
36
37### XComponent<sup>12+</sup>
38
39XComponent(options: XComponentOptions)
40
41创建XComponent组件,支持在ArkTS侧获取SurfaceId、注册XComponent持有的Surface的生命周期回调和触摸、鼠标、按键等组件事件回调,支持AI分析。
42
43**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
44
45**系统能力:** SystemCapability.ArkUI.ArkUI.Full
46
47**参数:**
48
49| 参数名  | 类型                                | 必填 | 说明                           |
50| ------- | --------------------------------------- | ---- | ------------------------------ |
51| options | [XComponentOptions](#xcomponentoptions12) | 是   | 定义XComponent的具体配置参数。 |
52
53### XComponent<sup>10+</sup>
54
55XComponent(value: {id: string, type: XComponentType, libraryname?: string, controller?: XComponentController})
56
57创建XComponent组件,支持Native侧触发XComponent生命周期回调。
58
59该接口从API version 12开始不再演进,推荐使用[XComponent(options: XComponentOptions)](#xcomponent12)。
60
61**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
62
63**系统能力:** SystemCapability.ArkUI.ArkUI.Full
64
65**参数:**
66
67| 参数名      | 类型                                      | 必填 | 说明                                                         |
68| ----------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
69| id          | string                                        | 是   | 组件的唯一标识,支持最大的字符串长度128。                    |
70| type        | [XComponentType](ts-appendix-enums.md#xcomponenttype10)   | 是   | 用于指定XComponent组件类型。                                 |
71| libraryname | string                                        | 否   | 用Native层编译输出动态库名称(对应的动态库不支持跨模块加载),仅类型为SURFACE或TEXTURE时有效。 |
72| controller  | [XComponentController](#xcomponentcontroller) | 否   | 给组件绑定一个控制器,通过控制器调用组件方法,仅类型为SURFACE或TEXTURE时有效。 |
73
74### XComponent<sup>(deprecated)</sup>
75
76XComponent(value: {id: string, type: string, libraryname?: string, controller?: XComponentController})
77
78**说明:**
79
80从API version 12开始废弃,建议使用[XComponent(options: XComponentOptions)](#xcomponent12)替代。
81
82**系统能力:** SystemCapability.ArkUI.ArkUI.Full
83
84**参数:**
85
86| 参数名      | 类型                                      | 必填 | 说明                                                         |
87| ----------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
88| id          | string                                        | 是   | 组件的唯一标识,支持最大的字符串长度128。                    |
89| type        | string                                        | 是   | 用于指定XComponent组件类型,可选值仅有两个为:<br/>-"surface":用于EGL/OpenGLES和媒体数据写入,开发者定制的绘制内容单独展示到屏幕上。<br/>-"component"<sup>9+</sup> :XComponent将变成一个容器组件,并可在其中执行非UI逻辑以动态加载显示内容。<br/>其他值均会被视为"surface"类型 |
90| libraryname | string                                        | 否   | 应用Native层编译输出动态库名称(对应的动态库不支持跨模块加载),仅XComponent类型为"surface"时有效。 |
91| controller  | [XComponentcontroller](#xcomponentcontroller) | 否   | 给组件绑定一个控制器,通过控制器调用组件方法,仅XComponent类型为"surface"时有效。 |
92
93## XComponentOptions<sup>12+</sup>
94
95定义XComponent的具体配置参数。
96
97**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
98
99**系统能力:** SystemCapability.ArkUI.ArkUI.Full
100
101| 名称 | 类型 | 只读 | 可选 | 说明 |
102| -------- | -------- | -------- | -------- | -------- |
103| type | [XComponentType](ts-appendix-enums.md#xcomponenttype10)         | 否 | 否   | 用于指定XComponent组件类型。 |
104| controller | [XComponentController](#xcomponentcontroller) | 否 | 否 | 给组件绑定一个控制器,通过控制器调用组件方法,仅类型为SURFACE或TEXTURE时有效。 |
105| imageAIOptions | [ImageAIOptions](ts-image-common.md#imageaioptions12) | 否 | 是 | 给组件设置一个AI分析选项,通过此项可配置分析类型或绑定一个分析控制器。 |
106
107## NativeXComponentParameters<sup>19+</sup>
108
109定义XComponent的具体配置参数。通过这种构造参数创建的XComponent,可以将其对应的[FrameNode](../js-apis-arkui-frameNode.md)对象传递至Native侧,使用NDK接口进行Surface生命周期的相关设置和[监听组件事件](../../../ui/ndk-listen-to-component-events.md)。
110
111**原子化服务API:** 从API version 19开始,该接口支持在原子化服务中使用。
112
113**系统能力:** SystemCapability.ArkUI.ArkUI.Full
114
115| 名称 | 类型 | 只读 | 可选 | 说明 |
116| -------- | -------- | -------- | -------- | -------- |
117| type | [XComponentType](ts-appendix-enums.md#xcomponenttype10)         | 否 | 否   | 用于指定XComponent组件类型。 |
118| imageAIOptions | [ImageAIOptions](ts-image-common.md#imageaioptions12) | 否 | 是 | 给组件设置一个AI分析选项,通过此项可配置分析类型或绑定一个分析控制器。 |
119
120## 属性
121除支持通用属性外,还支持以下属性:
122  >
123  > **说明:**
124  >
125  > 不支持foregroundColor、obscured和pixelStretchEffect属性,并且type为SURFACE类型时也不支持动态属性设置、自定义绘制、背景设置(backgroundColor除外)、图像效果(shadow除外)、maskShape和foregroundEffect属性。
126  >
127  > 对于TEXTURE和SURFACE类型的XComponent组件,当不设置[renderFit](./ts-universal-attributes-renderfit.md)属性时,取默认值为RenderFit.RESIZE_FILL128  >
129  > 对于SURFACE类型的XComponent组件,背景色设置为不透明的纯黑色,在API version 18之前,其[renderFit](./ts-universal-attributes-renderfit.md)通用属性仅支持设置为RenderFit.RESIZE_FILL;在API version 18及之后,支持所有的RenderFit枚举值。
130  >
131  > 对于使用[ArkUI NDK接口](../../../ui/ndk-access-the-arkts-page.md)创建的XComponent组件,不支持使用属性获取函数[getAttribute](../capi-arkui-nativemodule-arkui-nativenodeapi-1.md#getattribute)获取其renderFit属性值。
132
133### enableAnalyzer<sup>12+</sup>
134
135enableAnalyzer(enable: boolean)
136
137设置组件支持AI分析,当前支持主体识别、文字识别和对象查找等功能。
138本功能需要搭配XComponentController的[StartImageAnalyzer](#startimageanalyzer12)和[StopImageAnalyzer](#stopimageanalyzer12)一起使用。
139不能和[overlay](ts-universal-attributes-overlay.md)属性同时使用,两者同时设置时overlay中CustomBuilder属性将失效。该特性依赖设备能力。
140
141**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
142
143**系统能力:** SystemCapability.ArkUI.ArkUI.Full
144
145**参数:**
146
147| 参数名 | 类型 | 必填 | 说明 |
148| -------- | -------- | -------- | -------- |
149| enable | boolean | 是 | 是否启用图像分析功能。<br/>true:开启图像分析;false:关闭图像分析。<br/>默认值:false |
150
151  > **说明:**
152  >
153  > 仅type为SURFACE和TEXTURE时该功能有效。
154
155### enableSecure<sup>13+</sup>
156
157enableSecure(isSecure: boolean)
158
159防止组件内自绘制内容被截屏、录屏。
160
161**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
162
163**系统能力:** SystemCapability.ArkUI.ArkUI.Full
164
165**参数:**
166
167| 参数名   | 类型    | 必填 | 说明                   |
168| -------- | ------- | ---- | ---------------------- |
169| isSecure | boolean | 是   | 是否开启隐私图层模式。<br/>true:开启隐私图层模式;false:关闭隐私图层模式。<br/>默认值:false |
170
171  > **说明:**
172  >
173  > 仅type为SURFACE时有效。
174  >
175  > 不支持[ArkUI NDK接口](../../../ui/ndk-build-ui-overview.md)创建的XComponent组件。
176
177### hdrBrightness<sup>20+</sup>
178
179hdrBrightness(brightness: number)
180
181用于调整组件播放HDR视频的亮度。
182
183**原子化服务API:** 从API version 20开始,该接口支持在原子化服务中使用。
184
185**系统能力:** SystemCapability.ArkUI.ArkUI.Full
186
187**参数:**
188
189| 参数名   | 类型    | 必填 | 说明                   |
190| -------- | ------- | ---- | ---------------------- |
191| brightness | number | 是   | 用于调整组件播放HDR视频的亮度; brightness的取值范围为0.0~1.0; 小于0.0的值等价于0.0,大于1.0的值等价于1.0,异常值按1.0处理; 0.0 表示SDR视频的亮度,1.0 表示HDR视频的亮度。<br/>默认值:1.0 |
192
193  > **说明:**
194  >
195  > 仅type为SURFACE时有效。
196  >
197  > 不支持[ArkUI NDK接口](../../../ui/ndk-build-ui-overview.md)创建的XComponent组件。
198
199## 事件
200
201从API version 12开始,type为SURFACE或TEXTURE时,支持[通用事件](ts-component-general-events.md)。
202
203> **说明:**
204>
205> 当配置libraryname参数时,[点击事件](ts-universal-events-click.md)、[触摸事件](ts-universal-events-touch.md)、[挂载卸载事件](ts-universal-events-show-hide.md)、[按键事件](ts-universal-events-key.md)、[焦点事件](ts-universal-focus-event.md)、[鼠标事件](ts-universal-mouse-key.md)仅响应C-API侧事件接口。
206
207仅type为SURFACE或TEXTURE时以下事件有效:
208
209### onLoad
210
211onLoad(callback: OnNativeLoadCallback )
212
213插件加载完成时回调事件。
214
215**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
216
217**系统能力:** SystemCapability.ArkUI.ArkUI.Full
218
219**参数:**
220
221| 参数名   | 类型   | 必填   | 说明                                       |
222| ----- | ------ | ---- | ---------------------------------------- |
223| callback | [OnNativeLoadCallback](#onnativeloadcallback18) | 是    | XComponent持有的Surface创建后回调事件。 |
224
225### onDestroy
226
227onDestroy(event: VoidCallback )
228
229插件卸载完成时回调事件。
230
231**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
232
233**系统能力:** SystemCapability.ArkUI.ArkUI.Full
234
235**参数:**
236
237| 参数名   | 类型   | 必填   | 说明                                       |
238| ----- | ------ | ---- | ---------------------------------------- |
239| event | [VoidCallback](ts-types.md#voidcallback12) | 是    | XComponent销毁后回调事件。 |
240
241## OnNativeLoadCallback<sup>18+</sup>
242
243type OnNativeLoadCallback = (event?: object) =\> void
244
245XComponent持有的Surface创建后回调事件。
246
247**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
248
249**系统能力:** SystemCapability.ArkUI.ArkUI.Full
250
251**参数:**
252
253| 参数名   | 类型   | 必填   | 说明                                       |
254| ----- | ------ | ---- | ---------------------------------------- |
255| event | object | 否    | 获取XComponent实例对象的context,context上挂载的方法由开发者在Native层定义。 |
256
257## XComponentController
258
259XComponent组件的控制器,可以将此对象绑定至XComponent组件,然后通过控制器来调用组件方法。
260
261**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
262
263**系统能力:** SystemCapability.ArkUI.ArkUI.Full
264
265### constructor
266
267constructor()
268
269XComponentController的构造函数。
270
271**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
272
273**系统能力:** SystemCapability.ArkUI.ArkUI.Full
274
275**示例:**
276
277  ```ts
278  xcomponentController: XComponentController = new XComponentController();
279  ```
280
281### getXComponentSurfaceId<sup>9+</sup>
282
283getXComponentSurfaceId(): string
284
285获取XComponent对应Surface的ID,仅XComponent类型为SURFACE("surface")或TEXTURE时有效。
286
287**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
288
289**系统能力:** SystemCapability.ArkUI.ArkUI.Full
290
291**返回值:**
292
293| 类型     | 说明                      |
294| ------ | ----------------------- |
295| string | XComponent持有Surface的ID。 |
296
297> **说明:**
298>
299> 使用自定义组件节点创建XComponent组件时,因为onLoad回调触发时机早于[onSurfaceCreated](#onsurfacecreated12),所以在onLoad回调中调用[getXComponentSurfaceId](#getxcomponentsurfaceid9)获取surfaceId会失败,建议在[onSurfaceCreated](#onsurfacecreated12)回调中获取。
300
301**示例:**
302
303  ```ts
304  // xxx.ets
305  @Entry
306  @Component
307  struct Index {
308    myXComponentController: XComponentController = new XComponentController();
309
310    build() {
311      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
312        XComponent({
313          type: XComponentType.SURFACE,
314          controller: this.myXComponentController
315        })
316          .onLoad(() => {
317            let surfaceId: string = this.myXComponentController.getXComponentSurfaceId();
318            console.info("XComponent SurfaceId: " + surfaceId);
319          })
320      }
321    }
322  }
323  ```
324
325### setXComponentSurfaceSize<sup>(deprecated)</sup>
326
327setXComponentSurfaceSize(value: {surfaceWidth: number, surfaceHeight: number}): void
328
329设置XComponent持有Surface的宽度和高度,仅XComponent类型为SURFACE("surface")或TEXTURE时有效。
330
331该接口从API version 12开始废弃,建议使用[setXComponentSurfaceRect](#setxcomponentsurfacerect12)替代。
332
333**系统能力:** SystemCapability.ArkUI.ArkUI.Full
334
335**参数:**
336
337| 参数名           | 类型   | 必填   | 说明                      |
338| ------------- | ------ | ---- | ----------------------- |
339| surfaceWidth  | number | 是    | XComponent持有Surface的宽度。 |
340| surfaceHeight | number | 是    | XComponent持有Surface的高度。 |
341
342
343### getXComponentContext
344
345getXComponentContext(): Object
346
347获取XComponent实例对象的context,仅XComponent类型为SURFACE("surface")或TEXTURE时有效。
348
349**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
350
351**系统能力:** SystemCapability.ArkUI.ArkUI.Full
352
353**返回值:**
354
355| 类型   | 说明                                                         |
356| ------ | ------------------------------------------------------------ |
357| Object | 获取XComponent实例对象的context,context包含的具体接口方法由开发者自定义,context内容与onLoad回调中的第一个参数一致。 |
358
359### setXComponentSurfaceRect<sup>12+</sup>
360
361setXComponentSurfaceRect(rect: SurfaceRect): void
362
363设置XComponent持有Surface的显示区域,包括宽高和相对于组件左上角的位置坐标,仅XComponent类型为SURFACE("surface")或TEXTURE时有效。
364
365**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
366
367**系统能力:** SystemCapability.ArkUI.ArkUI.Full
368
369**参数:**
370
371| 参数名 | 类型                             | 必填 | 说明                              |
372| ------ | ------------------------------------ | ---- | --------------------------------- |
373| rect   | [SurfaceRect](#surfacerect12对象说明) | 是   | XComponent持有Surface的显示区域。 |
374
375> **说明:**
376>
377> rect参数中的offsetX/offsetY不设置或传入异常值时,Surface显示区域相对于XComponent左上角x/y轴的偏移效果默认按照居中显示。
378>
379> rect参数中的surfaceWidth和surfaceHeight存在0、负数或其他异常值时,调用该接口设置显示区域不生效。未调用该接口主动设置Surface显示区域时,surfaceWidth默认与组件宽度一致,surfaceHeight默认与组件高度一致。
380>
381> 该方法优先级高于[border](ts-universal-attributes-border.md#border)、[padding](ts-universal-attributes-size.md#padding)等可以改变内容偏移和大小的属性。
382
383### getXComponentSurfaceRect<sup>12+</sup>
384
385getXComponentSurfaceRect(): SurfaceRect
386
387获取XComponent持有Surface的显示区域,包括宽高和相对于组件左上角的位置坐标,仅XComponent类型为SURFACE("surface")或TEXTURE时有效。
388
389**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
390
391**系统能力:** SystemCapability.ArkUI.ArkUI.Full
392
393**返回值:**
394
395| 类型                                 | 说明                                  |
396| ------------------------------------ | ------------------------------------- |
397| [SurfaceRect](#surfacerect12对象说明) | 获取XComponent持有Surface的显示区域。 |
398
399### onSurfaceCreated<sup>12+</sup>
400
401onSurfaceCreated(surfaceId: string): void
402
403当XComponent持有的Surface创建后进行该回调,仅XComponent类型为SURFACE("surface")或TEXTURE时有效。
404
405**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
406
407**系统能力:** SystemCapability.ArkUI.ArkUI.Full
408
409**参数:**
410
411| 参数名    | 类型 | 必填 | 说明                                              |
412| --------- | -------- | ---- | ------------------------------------------------- |
413| surfaceId | string   | 是   | 回调该方法的时候,绑定XComponent持有Surface的ID。 |
414
415> **说明:**
416>
417> 仅当XComponent组件未设置libraryname参数时,会进行该回调。
418
419### onSurfaceChanged<sup>12+</sup>
420
421onSurfaceChanged(surfaceId: string, rect: SurfaceRect): void
422
423当XComponent持有的Surface大小改变后(包括首次创建时的大小改变)进行该回调,仅XComponent类型为SURFACE("surface")或TEXTURE时有效。
424
425**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
426
427**系统能力:** SystemCapability.ArkUI.ArkUI.Full
428
429**参数:**
430
431| 参数名    | 类型                              | 必填 | 说明                                                    |
432| --------- | ------------------------------------- | ---- | ------------------------------------------------------- |
433| surfaceId | string                                | 是   | 回调该方法的时候,绑定XComponent持有Surface的ID。       |
434| rect      | [SurfaceRect](#surfacerect12对象说明) | 是   | 回调该方法的时候,绑定XComponent持有Surface的显示区域。 |
435
436> **说明:**
437>
438> 仅当XComponent组件未设置libraryname参数时,会进行该回调。
439
440### onSurfaceDestroyed<sup>12+</sup>
441
442onSurfaceDestroyed(surfaceId: string): void
443
444当XComponent持有的Surface销毁后进行该回调,仅XComponent类型为SURFACE("surface")或TEXTURE时有效。
445
446**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
447
448**系统能力:** SystemCapability.ArkUI.ArkUI.Full
449
450**参数:**
451
452| 参数名    | 类型 | 必填 | 说明                                              |
453| --------- | -------- | ---- | ------------------------------------------------- |
454| surfaceId | string   | 是   | 回调该方法的时候,绑定XComponent持有Surface的ID。 |
455
456> **说明:**
457>
458> 仅当XComponent组件未设置libraryname参数时,会进行该回调。
459
460### startImageAnalyzer<sup>12+</sup>
461
462startImageAnalyzer(config: ImageAnalyzerConfig): Promise\<void>
463
464配置AI分析并启动AI分析功能,使用前需先[启用图像AI分析能力](#enableanalyzer12)。使用Promise异步回调。<br>该方法调用时,将截取调用时刻的画面帧进行分析,使用时需注意启动分析的时机,避免出现画面和分析内容不一致的情况。<br>若该方法尚未执行完毕,此时重复调用,则会触发错误回调。
465
466> **说明:**
467>
468> 分析类型不支持动态修改。
469> 该特性依赖设备能力,不支持该能力的情况下,将返回错误码。
470
471**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
472
473**系统能力:** SystemCapability.ArkUI.ArkUI.Full
474
475**参数:**
476
477| 参数名 | 类型      | 必填 | 说明                                                                   |
478| ------ | --------- | ---- | ---------------------------------------------------------------------- |
479| config   | [ImageAnalyzerConfig](ts-image-common.md#imageanalyzerconfig12) | 是   | 执行AI分析所需要的入参,用于配置AI分析功能。 |
480
481**返回值:**
482
483| 类型              | 说明                                 |
484| ----------------- | ------------------------------------ |
485| Promise\<void>  | Promise对象,无返回结果。用于获取AI分析是否成功执行。 |
486
487**错误码:**
488
489以下错误码的详细介绍请参见[AI分析类库错误码](errorcode-image-analyzer.md)。
490
491| 错误码ID | 错误信息                                      |
492| -------- | -------------------------------------------- |
493| 110001 | Image analysis feature is unsupported.               |
494| 110002 | Image analysis is currently being executed.  |
495| 110003 | Image analysis is stopped.  |
496
497### stopImageAnalyzer<sup>12+</sup>
498
499stopImageAnalyzer(): void
500
501停止AI分析功能,AI分析展示的内容将被销毁。
502
503> **说明:**
504>
505> 在startImageAnalyzer方法未返回结果时调用本方法,会触发其错误回调。
506> 该特性依赖设备能力。
507
508**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
509
510**系统能力:** SystemCapability.ArkUI.ArkUI.Full
511
512### setXComponentSurfaceRotation<sup>12+</sup>
513
514setXComponentSurfaceRotation(rotationOptions: SurfaceRotationOptions): void
515
516设置XComponent持有Surface在屏幕旋转时是否锁定方向,仅XComponent类型为SURFACE("surface")时有效。
517
518**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
519
520**系统能力:** SystemCapability.ArkUI.ArkUI.Full
521
522**参数:**
523
524| 参数名 | 类型                             | 必填 | 说明                              |
525| ------ | ------------------------------------ | ---- | --------------------------------- |
526| rotationOptions   | [SurfaceRotationOptions](#surfacerotationoptions12对象说明) | 是 | 设置XComponent持有Surface在屏幕旋转时是否锁定方向。 |
527
528> **说明:**
529>
530> rotationOptions未配置时,默认XComponent持有Surface在屏幕旋转时不锁定方向,跟随屏幕进行旋转。
531>
532> 仅在屏幕旋转过程中生效,旋转完成后不再锁定Surface。
533>
534> 仅在屏幕旋转90°,即发生横竖屏切换时生效。
535>
536> 锁定旋转后的Buffer宽高需要保持不变,否则会有拉伸问题。
537
538### getXComponentSurfaceRotation<sup>12+</sup>
539
540getXComponentSurfaceRotation(): Required\<SurfaceRotationOptions>
541
542获取XComponent持有Surface在屏幕旋转时是否锁定方向的设置,仅XComponent类型为SURFACE("surface")时有效。
543
544**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
545
546**系统能力:** SystemCapability.ArkUI.ArkUI.Full
547
548**返回值:**
549
550| 类型                                 | 说明                                  |
551| ------------------------------------ | ------------------------------------- |
552| Required<[SurfaceRotationOptions](#surfacerotationoptions12对象说明)> | 获取XComponent持有Surface在屏幕旋转时是否锁定方向的设置。 |
553
554### lockCanvas<sup>20+</sup>
555
556lockCanvas(): DrawingCanvas | null
557
558返回可用于向XComponent上绘制内容的画布对象。具体绘制方法请参考[Canvas](../../apis-arkgraphics2d/arkts-apis-graphics-drawing-Canvas.md)。
559
560**原子化服务API:** 从API version 20开始,该接口支持在原子化服务中使用。
561
562**系统能力:** SystemCapability.ArkUI.ArkUI.Full
563
564**返回值:**
565| 类型                                 | 说明                                  |
566| ------------------------------------ | ------------------------------------- |
567| [DrawingCanvas](ts-drawingrenderingcontext.md#drawingcanvas12对象说明) \| null | 可用于向XComponent区域绘制的画布对象或者空对象null。 |
568
569> **说明:**
570>
571> 如果当前XComponent状态无法获取画布对象则将返回null。原因通常为:
572>
573> 1. XComponent持有的Surface未创建完成(可通过设置[onLoad](#onload)/[onSurfaceCreated](#onsurfacecreated12)回调来确定,此回调触发时,Surface已创建完成)。
574>
575> 2. 之前已经调用过lockCanvas来获取过画布对象,且该画布对象未调用[unlockCanvasAndPost](#unlockcanvasandpost20)去释放。
576>
577> 只支持TEXTURE和SURFACE模式。
578>
579> 使用此接口后,同时在NDK侧获取NativeWindow并调用相关接口进行绘制,可能出现缓冲区竞争和上下文冲突而发生绘制画面错误等异常,因此不允许使用。
580>
581> 此接口需要和[unlockCanvasAndPost](#unlockcanvasandpost20)接口配对使用,具体参考[示例3使用画布对象在XComponent上绘制内容](#示例3使用画布对象在xcomponent上绘制内容)。
582
583### unlockCanvasAndPost<sup>20+</sup>
584
585unlockCanvasAndPost(canvas: DrawingCanvas): void
586
587将画布对象中的内容绘制在XComponent区域,并释放该画布对象。
588
589**原子化服务API:** 从API version 20开始,该接口支持在原子化服务中使用。
590
591**系统能力:** SystemCapability.ArkUI.ArkUI.Full
592
593**参数:**
594| 参数名 | 类型 | 必填 | 说明 |
595| -------- | -------- | -------- | -------- |
596| canvas | [DrawingCanvas](ts-drawingrenderingcontext.md#drawingcanvas12对象说明) | 是 | 之前调用lockCanvas方法返回的画布对象。 |
597
598> **说明:**
599>
600> 1. 画布对象调用unlockCanvasAndPost释放后,不可再使用该画布对象。
601>
602> 2. 只支持TEXTURE和SURFACE模式。
603>
604> 3. 使用此接口后,同时在NDK侧获取NativeWindow并调用相关接口进行绘制,可能出现缓冲区竞争和上下文冲突而发生绘制画面错误等异常,因此不允许使用。
605>
606> 4. 此接口需要和[lockCanvas](#lockcanvas20)接口配对使用,具体参考[示例3使用画布对象在XComponent上绘制内容](#示例3使用画布对象在xcomponent上绘制内容)。
607
608## SurfaceRotationOptions<sup>12+</sup>对象说明
609
610用于描述XComponent持有Surface在屏幕旋转时是否锁定方向的设置。
611
612**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
613
614**系统能力:** SystemCapability.ArkUI.ArkUI.Full
615
616| 名称          | 类型   | 只读 | 可选 | 说明                                                         |
617| ------------- | ------ | ------ | ---- | ------------------------------------------------------------ |
618| lock       | boolean | 否 | 是   | Surface在屏幕旋转时是否锁定方向,未设置时默认取值为false,即不锁定方向。<br/>true:锁定方向;false:不锁定方向。 |
619
620## SurfaceRect<sup>12+</sup>对象说明
621
622用于描述XComponent持有Surface的显示区域。
623
624**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
625
626**系统能力:** SystemCapability.ArkUI.ArkUI.Full
627
628| 名称          | 类型   | 只读 | 可选 | 说明                                                         |
629| ------------- | ------ | ------ | ---- | ------------------------------------------------------------ |
630| offsetX       | number | 否   | 是   | Surface显示区域相对于XComponent组件左上角的x轴坐标,单位:px。 |
631| offsetY       | number | 否   | 是   | Surface显示区域相对于XComponent组件左上角的y轴坐标,单位:px。 |
632| surfaceWidth  | number | 否   | 否   | Surface显示区域的宽度,单位:px。                            |
633| surfaceHeight | number | 否   | 否   | Surface显示区域的高度,单位:px。                            |
634
635> **说明:**
636>
637> surfaceWidth和surfaceHeight属性在未调用[setXComponentSurfaceRect](ts-basic-components-xcomponent.md#setxcomponentsurfacerect12)也未设置[border](ts-universal-attributes-border.md#border)和[padding](ts-universal-attributes-size.md#padding)等属性时,其取值大小为XComponent组件的大小。
638>
639> surfaceWidth和surfaceHeight属性的取值都不可超过8192px,否则会导致渲染异常。
640>
641> 沉浸式场景下,默认布局的SurfaceRect不包括安全区,需调用[setXComponentSurfaceRect](ts-basic-components-xcomponent.md#setxcomponentsurfacerect12)接口主动设置Surface显示区域达到沉浸式效果。
642
643## 示例
644
645示例效果请以真机运行为准,当前DevEco Studio预览器不支持。
646
647
648### 示例1(图像AI分析功能)
649
650使用enableAnalyzer属性开启图像AI分析功能。可通过XComponentController控制开始、停止图形AI分析。
651
652<!--RP1-->
653> **说明:**
654>
655> 本示例画图逻辑具体实现(和nativeRender相关的函数实现)可以参考[ArkTS XComponent示例](https://gitcode.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Native/ArkTSXComponent)656<!--RP1End-->
657
658```ts
659// xxx.ets
660import { BusinessError } from '@kit.BasicServicesKit';
661import nativeRender from 'libnativerender.so';// 开发者自己实现的so,详见上述说明。
662
663class CustomXComponentController extends XComponentController {
664  onSurfaceCreated(surfaceId: string): void {
665    console.info(`onSurfaceCreated surfaceId: ${surfaceId}`);
666    nativeRender.SetSurfaceId(BigInt(surfaceId));
667  }
668
669  onSurfaceChanged(surfaceId: string, rect: SurfaceRect): void {
670    console.info(`onSurfaceChanged surfaceId: ${surfaceId}, rect: ${JSON.stringify(rect)}}`);
671    nativeRender.ChangeSurface(BigInt(surfaceId), rect.surfaceWidth, rect.surfaceHeight);
672  }
673
674  onSurfaceDestroyed(surfaceId: string): void {
675    console.info(`onSurfaceDestroyed surfaceId: ${surfaceId}`);
676    nativeRender.DestroySurface(BigInt(surfaceId));
677  }
678}
679
680@Entry
681@Component
682struct XComponentExample {
683  xComponentController: XComponentController = new CustomXComponentController();
684  private config: ImageAnalyzerConfig = {
685    types: [ImageAnalyzerType.SUBJECT, ImageAnalyzerType.TEXT]
686  };
687  private aiController: ImageAnalyzerController = new ImageAnalyzerController();
688  private options: ImageAIOptions = {
689    types: [ImageAnalyzerType.SUBJECT, ImageAnalyzerType.TEXT],
690    aiController: this.aiController
691  };
692  @State xcWidth: string = "720px";
693  @State xcHeight: string = "720px";
694  @State currentStatus: string = "index";
695
696  build() {
697    Column({ space: 5 }) {
698      Row() {
699        Text('Native XComponent Sample')
700          .fontSize('24fp')
701          .fontWeight(500)
702          .margin({
703            left: 24,
704            top: 12
705          })
706      }
707      .margin({ top: 24 })
708      .width('100%')
709      .height(56)
710
711      XComponent({
712        type: XComponentType.SURFACE,
713        controller: this.xComponentController,
714        imageAIOptions: this.options
715      })
716        .width(this.xcWidth)
717        .height(this.xcHeight)
718        .enableAnalyzer(true)
719        .onClick(() => {
720          let surfaceId = this.xComponentController.getXComponentSurfaceId();
721          nativeRender.ChangeColor(BigInt(surfaceId));
722          let hasChangeColor: boolean = false;
723          if (nativeRender.GetXComponentStatus(BigInt(surfaceId))) {
724            hasChangeColor = nativeRender.GetXComponentStatus(BigInt(surfaceId)).hasChangeColor;
725          }
726          if (hasChangeColor) {
727            this.currentStatus = "change color";
728          }
729        })
730      Text(this.currentStatus)
731        .fontSize('24fp')
732        .fontWeight(500)
733      Column() {
734        Button('start AI analyze')
735          .onClick(() => {
736            this.xComponentController.startImageAnalyzer(this.config)
737              .then(() => {
738                console.info("analysis complete");
739              })
740              .catch((error: BusinessError) => {
741                console.error("error code: " + error.code);
742              })
743          })
744          .margin(2)
745        Button('stop AI analyze')
746          .onClick(() => {
747            this.xComponentController.stopImageAnalyzer();
748          })
749          .margin(2)
750        Button('get analyzer types')
751          .onClick(() => {
752            this.aiController.getImageAnalyzerSupportTypes();
753          })
754          .margin(2)
755        Button('Draw Star')
756          .fontSize('16fp')
757          .fontWeight(500)
758          .margin({ bottom: 24 })
759          .onClick(() => {
760            let surfaceId = this.xComponentController.getXComponentSurfaceId();
761            this.xComponentController.getXComponentSurfaceRect();
762            nativeRender.DrawPattern(BigInt(surfaceId));
763            let hasDraw: boolean = false;
764            if (nativeRender.GetXComponentStatus(BigInt(surfaceId))) {
765              hasDraw = nativeRender.GetXComponentStatus(BigInt(surfaceId)).hasDraw;
766            }
767            if (hasDraw) {
768              this.currentStatus = "draw star";
769            }
770          })
771          .margin(2)
772      }.justifyContent(FlexAlign.Center)
773    }
774    .width("100%")
775  }
776}
777```
778![AI示例运行图](./figures/AIXComponent.gif)
779
780
781### 示例2(在surface旋转过程中锁定)
782
783通过setXComponentSurfaceRotation设置surface在屏幕旋转过程中锁定方向,不跟随屏幕进行旋转。
784
785> **说明:**
786>
787> 本示例画图逻辑具体实现(和nativeRender相关的函数实现)可以参考<!--RP2-->[ArkTS XComponent示例](https://gitcode.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Native/ArkTSXComponent)。<!--RP2End-->
788
789```ts
790// xxx.ets
791import nativeRender from 'libnativerender.so';
792
793class MyXComponentController extends XComponentController {
794  onSurfaceCreated(surfaceId: string): void {
795    console.info(`onSurfaceCreated surfaceId: ${surfaceId}`);
796    nativeRender.SetSurfaceId(BigInt(surfaceId));
797  }
798
799  onSurfaceChanged(surfaceId: string, rect: SurfaceRect): void {
800    console.info(`onSurfaceChanged surfaceId: ${surfaceId}, rect: ${JSON.stringify(rect)}}`);
801    nativeRender.ChangeSurface(BigInt(surfaceId), rect.surfaceWidth, rect.surfaceHeight);
802  }
803
804  onSurfaceDestroyed(surfaceId: string): void {
805    console.info(`onSurfaceDestroyed surfaceId: ${surfaceId}`);
806    nativeRender.DestroySurface(BigInt(surfaceId));
807  }
808}
809
810@Entry
811@Component
812struct Index {
813  @State isLock: boolean = true;
814  @State xc_width: number = 500;
815  @State xc_height: number = 700;
816  myXComponentController: XComponentController = new MyXComponentController();
817
818  build() {
819    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Start }) {
820      XComponent({
821        id: "XComponent",
822        type: XComponentType.SURFACE,
823        controller: this.myXComponentController
824      })
825        .onLoad(() => {
826          let surfaceRotation: SurfaceRotationOptions = { lock: this.isLock };
827          this.myXComponentController.setXComponentSurfaceRotation(surfaceRotation);
828          console.info("Surface getXComponentSurfaceRotation lock = " +
829          this.myXComponentController.getXComponentSurfaceRotation().lock);
830        })
831        .width(this.xc_width)
832        .height(this.xc_height)
833      Button("Draw")
834        .onClick(() => {
835          let surfaceId = this.myXComponentController.getXComponentSurfaceId();
836          nativeRender.DrawPattern(BigInt(surfaceId));
837        })
838    }
839  }
840}
841```
842
843### 示例3(使用画布对象在XComponent上绘制内容)
844
845从API version 20开始,该示例通过调用[lockCanvas](#lockcanvas20)返回画布对象,通过画布对象调用对应的绘制接口,再调用[unlockCanvasAndPost](#unlockcanvasandpost20)在XComponent上绘制内容。
846
847```ts
848// xxx.ets
849import { drawing } from '@kit.ArkGraphics2D';
850
851@Entry
852@Component
853struct Index {
854  private xcController: XComponentController = new XComponentController();
855  private mCanvas: DrawingCanvas | null = null;
856
857  build() {
858    Column() {
859      XComponent({ type: XComponentType.SURFACE, controller: this.xcController })
860        .width("80%")
861        .height("80%")
862        .onLoad(() => {
863          this.mCanvas = this.xcController.lockCanvas();
864          if (this.mCanvas) {
865            this.mCanvas.drawColor(255, 240, 250, 255); // 每次绘制前必须完全重绘整个XComponent区域,可以调用此方法实现
866            const brush = new drawing.Brush(); // 创建画刷对象
867            brush.setColor({ // 设置画刷的颜色
868              alpha: 255,
869              red: 39,
870              green: 135,
871              blue: 217
872            });
873            this.mCanvas.attachBrush(brush); // 绑定画刷到画布上
874            this.mCanvas.drawRect({ // 绘制一个矩形
875              left: 300,
876              right: 800,
877              top: 100,
878              bottom: 800
879            });
880            this.mCanvas.detachBrush(); // 将画刷与画布解绑
881            this.xcController.unlockCanvasAndPost(this.mCanvas);
882          }
883        })
884    }
885    .height('100%')
886    .width('100%')
887  }
888}
889```
890![DrawingCanvas示例图](./figures/DrawingCanvas.PNG)
891