1# XComponent 2 3**XComponent** provides a [surface](../../../ui/napi-xcomponent-guidelines.md#how-custom-drawing-works) for graphics rendering and media data input into your view. You can customize the position and size of the surface as needed. For details, see [Native XComponent](../../../ui/napi-xcomponent-guidelines.md). 4 5> **NOTE** 6> 7> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. 8 9 10## Child Components 11Not supported 12 13## APIs 14 15### XComponent<sup>19+</sup> 16 17XComponent(params: NativeXComponentParameters) 18 19Obtains an **XComponent** node instance on the native side, and registers the lifecycle callbacks for the surface held by the **XComponent** and the callbacks for component events, such as touch, mouse, and key events. 20 21**Atomic service API**: This API can be used in atomic services since API version 19. 22 23**System capability**: SystemCapability.ArkUI.ArkUI.Full 24 25**Parameters** 26 27| Name | Type | Mandatory| Description | 28| ------- | --------------------------------------- | ---- | ------------------------------ | 29| params | [NativeXComponentParameters](#nativexcomponentparameters19) | Yes | Options of the **XComponent**.| 30 31### XComponent<sup>12+</sup> 32 33XComponent(options: XComponentOptions) 34 35Creates an **XComponent** component, allowing you to obtain the **SurfaceId** value on the ArkTS side, register the lifecycle callbacks for the surface held by the **XComponent** and the callbacks for component events such as touch, mouse, and key events, and configure the AI analyzer feature. 36 37**Atomic service API**: This API can be used in atomic services since API version 12. 38 39**System capability**: SystemCapability.ArkUI.ArkUI.Full 40 41**Parameters** 42 43| Name | Type | Mandatory| Description | 44| ------- | --------------------------------------- | ---- | ------------------------------ | 45| options | [XComponentOptions](#xcomponentoptions12) | Yes | Options of the **XComponent**.| 46 47### XComponent<sup>10+</sup> 48 49XComponent(value: {id: string, type: XComponentType, libraryname?: string, controller?: XComponentController}) 50 51Creates an **XComponent** component, whose lifecycle callbacks can be triggered from the native side. 52 53This API is deprecated since API version 12. You are advised to use [XComponent(options: XComponentOptions)](#xcomponent12) instead. 54 55**Atomic service API**: This API can be used in atomic services since API version 12. 56 57**System capability**: SystemCapability.ArkUI.ArkUI.Full 58 59**Parameters** 60 61| Name | Type | Mandatory| Description | 62| ----------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | 63| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters. | 64| type | [XComponentType](ts-appendix-enums.md#xcomponenttype10) | Yes | Type of the component. | 65| libraryname | string | No | Name of the dynamic library compiled and output by the native layer (the corresponding dynamic library does not support cross-module loading). This parameter is effective only when **type** is **SURFACE** or **TEXTURE**.| 66| controller | [XComponentController](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke methods of the component. This parameter is effective only when **type** is **SURFACE** or **TEXTURE**.| 67 68### XComponent<sup>(deprecated)</sup> 69 70XComponent(value: {id: string, type: string, libraryname?: string, controller?: XComponentController}) 71 72> **NOTE** 73> 74> This API is deprecated since API version 12. You are advised to use [XComponent(options: XComponentOptions)](#xcomponent12) instead. 75 76**System capability**: SystemCapability.ArkUI.ArkUI.Full 77 78**Parameters** 79 80| Name | Type | Mandatory| Description | 81| ----------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | 82| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters. | 83| type | string | Yes | Type of the component. The options are as follows:<br>- **"surface"**: The custom content is displayed individually on the screen. This option is used for displaying EGL/OpenGL ES and media data.<br>- **"component"**<sup>9+</sup>: The component acts a container where non-UI logic can be executed to dynamically load and display content.<br>Any other value is handled as **"surface"**.| 84| libraryname | string | No | Name of the dynamic library compiled and output by the native layer (the corresponding dynamic library does not support cross-module loading). This parameter is effective only when **type** is **"surface"**.| 85| controller | [XComponentcontroller](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke methods of the component. This parameter is valid only when the component type is **"surface"**.| 86 87## XComponentOptions<sup>12+</sup> 88 89Defines the options of the **XComponent**. 90 91**Atomic service API**: This API can be used in atomic services since API version 12. 92 93**System capability**: SystemCapability.ArkUI.ArkUI.Full 94 95| Name| Type| Read-Only| Optional| Description| 96| -------- | -------- | -------- | -------- | -------- | 97| type | [XComponentType](ts-appendix-enums.md#xcomponenttype10) | No| No | Type of the component.| 98| controller | [XComponentController](#xcomponentcontroller) | No| No| Controller bound to the component, which can be used to invoke methods of the component. This parameter is effective only when **type** is **SURFACE** or **TEXTURE**.| 99| imageAIOptions | [ImageAIOptions](ts-image-common.md#imageaioptions) | No| Yes| AI image analysis options. You can configure the analysis type or bind an analyzer controller through this parameter.| 100 101## NativeXComponentParameters<sup>19+</sup> 102 103Defines the options of the **XComponent**. This API allows the corresponding [FrameNode](../js-apis-arkui-frameNode.md) to be passed to the native side to use NDK APIs for building UIs, [listening for component events](../../../ui/ndk-listen-to-component-events.md), and managing surface lifecycle settings. 104 105**Atomic service API**: This API can be used in atomic services since API version 19. 106 107**System capability**: SystemCapability.ArkUI.ArkUI.Full 108 109| Name| Type| Read-Only| Optional| Description| 110| -------- | -------- | -------- | -------- | -------- | 111| type | [XComponentType](ts-appendix-enums.md#xcomponenttype10) | No| No | Type of the component.| 112| imageAIOptions | [ImageAIOptions](ts-image-common.md#imageaioptions) | No| Yes| AI image analysis options. You can configure the analysis type or bind an analyzer controller through this parameter.| 113 114## Attributes 115In addition to universal attributes, the following attributes are supported. 116 > 117 > **NOTE** 118 > 119 > The **foregroundColor**, **obscured**, and **pixelStretchEffect** attributes are not supported. When **type** is set to **SURFACE**, the following are not supported either: attribute modifier, custom drawing, background options (except **backgroundColor**), image effects (except **shadow**), **maskShape**, and **foregroundEffect** attributes. 120 > 121 > For the **XComponent** component of the TEXTURE or SURFACE type, if the [renderFit](./ts-universal-attributes-renderfit.md) attribute is not set, it defaults to **RenderFit.RESIZE_FILL**. 122 > 123 > For the XComponent component of the SURFACE type with an opaque black background color: In versions earlier than API version 18, the [renderFit](./ts-universal-attributes-renderfit.md) attribute only supports RenderFit.RESIZE_FILL; since API version 18, the **renderFit** attribute supports all its available enum values. 124 > 125 > For the **XComponent** component created using the [ArkUI NDK API](../../../ui/ndk-access-the-arkts-page.md), the [getAttribute](../_ark_u_i___native_node_a_p_i__1.md#getattribute) function is not supported for obtaining the **renderFit** attribute value. 126 127### enableAnalyzer<sup>12+</sup> 128 129enableAnalyzer(enable: boolean) 130 131Sets whether to enable the AI image analyzer, which supports subject recognition, text recognition, and object lookup. 132For the settings to take effect, this attribute must be used together with [StartImageAnalyzer](#startimageanalyzer12) and [StopImageAnalyzer](#stopimageanalyzer12) of **XComponentController**. 133This feature cannot be used together with the [overlay](ts-universal-attributes-overlay.md) attribute. If both are set, the **CustomBuilder** attribute in **overlay** has no effect. This feature also depends on device capabilities. 134 135**Atomic service API**: This API can be used in atomic services since API version 12. 136 137**System capability**: SystemCapability.ArkUI.ArkUI.Full 138 139**Parameters** 140 141| Name| Type| Mandatory| Description| 142| -------- | -------- | -------- | -------- | 143| enable | boolean | Yes| Whether to enable the AI image analyzer.<br>true: Enable the image analysis function. false: Disable the image analysis function.<br>Default value: **false**.| 144 145 > **NOTE** 146 > 147 > This API has effect only when **type** is set to **SURFACE** or **TEXTURE**. 148 149### enableSecure<sup>13+</sup> 150 151enableSecure(isSecure: boolean) 152 153Sets whether to enable the secure surface to protect the content rendered within the component from being captured or recorded. 154 155**Atomic service API**: This API can be used in atomic services since API version 13. 156 157**System capability**: SystemCapability.ArkUI.ArkUI.Full 158 159**Parameters** 160 161| Name | Type | Mandatory| Description | 162| -------- | ------- | ---- | ---------------------- | 163| isSecure | boolean | Yes | Whether to enable the secure surface.<br>The value **true** means to enable the secure surface, and **false** means the opposite.<br>Default value: **false**.| 164 165 > **NOTE** 166 > 167 > This attribute is effective only when **type** is set to **SURFACE**. 168 > 169 > The **XComponent** created using the[ArkUI NDK APIs](../../../ui/ndk-build-ui-overview.md) is not supported. 170 171### hdrBrightness<sup>20+</sup> 172 173hdrBrightness(brightness: number) 174 175Sets the brightness of HDR video playback for the component. 176 177**Atomic service API**: This API can be used in atomic services since API version 20. 178 179**System capability**: SystemCapability.ArkUI.ArkUI.Full 180 181**Parameters** 182 183| Name | Type | Mandatory| Description | 184| -------- | ------- | ---- | ---------------------- | 185| brightness | number | Yes | Brightness of HDR video playback.<br>Value range: 0.0 to 1.0.<br>Values less than 0 are equivalent to 0, and values greater than 1 are equivalent to 1.<br>**0** indicates the brightness of the SDR video, and **1** indicates the brightness of the HDR video.| 186 187 > **NOTE** 188 > 189 > This attribute is effective only when **type** is set to **SURFACE**. 190 > 191 > The **XComponent** created using the[ArkUI NDK APIs](../../../ui/ndk-build-ui-overview.md) is not supported. 192 193## Events 194 195Since API version 12, the [universal events](ts-universal-events-click.md) are supported when **type** is set to **SURFACE** or **TEXTURE**. 196 197> **NOTE** 198> 199> When the **libraryname** parameter is set, [click events](ts-universal-events-click.md), [touch events](ts-universal-events-touch.md), [show/hide events](ts-universal-events-show-hide.md), [key events](ts-universal-events-key.md), [focus events](ts-universal-focus-event.md), and [mouse events](ts-universal-mouse-key.md) only respond to event APIs on the C API side. 200 201The following events are effective only when **type** is set to **SURFACE** or **TEXTURE**. 202 203### onLoad 204 205onLoad(callback: OnNativeLoadCallback ) 206 207Triggered when the plugin is loaded. 208 209**Atomic service API**: This API can be used in atomic services since API version 12. 210 211**System capability**: SystemCapability.ArkUI.ArkUI.Full 212 213**Parameters** 214 215| Name | Type | Mandatory | Description | 216| ----- | ------ | ---- | ---------------------------------------- | 217| callback | [OnNativeLoadCallback](#onnativeloadcallback18) | Yes | Callback after the surface held by the **XComponent** is created.| 218 219> **NOTE** 220> 221> When you create an **XComponent** using a custom component node, the **onLoad** callback is triggered before the [onSurfaceCreated](#onsurfacecreated12) callback. This means that calling [getXComponentSurfaceId](#getxcomponentsurfaceid9) in the **onLoad** callback will not return a valid **surfaceId**. You are advised to obtain the **surfaceId** in the [onSurfaceCreated](#onsurfacecreated12) callback instead. 222 223### onDestroy 224 225onDestroy(event: VoidCallback ) 226 227Triggered when the plugin is destroyed. 228 229**Atomic service API**: This API can be used in atomic services since API version 12. 230 231**System capability**: SystemCapability.ArkUI.ArkUI.Full 232 233**Parameters** 234 235| Name | Type | Mandatory | Description | 236| ----- | ------ | ---- | ---------------------------------------- | 237| event | [VoidCallback](ts-types.md#voidcallback12) | Yes | Callback after the **XComponent** is destroyed.| 238 239## OnNativeLoadCallback<sup>18+</sup> 240 241type OnNativeLoadCallback = (event?: object) =\> void 242 243Triggered after the surface held by the **XComponent** is created. 244 245**Atomic service API**: This API can be used in atomic services since API version 18. 246 247**System capability**: SystemCapability.ArkUI.ArkUI.Full 248 249**Parameters** 250 251| Name | Type | Mandatory | Description | 252| ----- | ------ | ---- | ---------------------------------------- | 253| event | object | No | Context of the **XComponent** object. The APIs contained in the context are defined at the native layer by developers.| 254 255## XComponentController 256 257Defines the controller of the **XComponent**. You can bind the controller to the **XComponent** to call the component APIs through the controller. 258 259**Atomic service API**: This API can be used in atomic services since API version 12. 260 261**System capability**: SystemCapability.ArkUI.ArkUI.Full 262 263### constructor 264 265constructor() 266 267A constructor used to create a **XComponentController** instance. 268 269```ts 270xcomponentController: XComponentController = new XComponentController(); 271``` 272 273**Atomic service API**: This API can be used in atomic services since API version 12. 274 275**System capability**: SystemCapability.ArkUI.ArkUI.Full 276 277### getXComponentSurfaceId<sup>9+</sup> 278 279getXComponentSurfaceId(): string 280 281Obtains the ID of the surface held by the **XComponent**, which can then be used for @ohos APIs. For details, see [Camera Management](../../apis-camera-kit/arkts-apis-camera.md). This API works only when **type** of the **XComponent** is set to **SURFACE("surface")** or **TEXTURE**. 282 283**Atomic service API**: This API can be used in atomic services since API version 12. 284 285**System capability**: SystemCapability.ArkUI.ArkUI.Full 286 287**Return value** 288 289| Type | Description | 290| ------ | ----------------------- | 291| string | ID of the surface held by the **XComponent**.| 292 293 294### setXComponentSurfaceSize<sup>(deprecated)</sup> 295 296setXComponentSurfaceSize(value: {surfaceWidth: number, surfaceHeight: number}): void 297 298Sets the width and height of the surface held by the **XComponent**. This API works only when **type** of the **XComponent** is set to **SURFACE("surface")** or **TEXTURE**. 299 300This API is deprecated since API version 12. You are advised to use [setXComponentSurfaceRect](#setxcomponentsurfacerect12) instead. 301 302**System capability**: SystemCapability.ArkUI.ArkUI.Full 303 304**Parameters** 305 306| Name | Type | Mandatory | Description | 307| ------------- | ------ | ---- | ----------------------- | 308| surfaceWidth | number | Yes | Width of the surface held by the **XComponent**.| 309| surfaceHeight | number | Yes | Height of the surface held by the **XComponent**.| 310 311 312### getXComponentContext 313 314getXComponentContext(): Object 315 316Obtains the context of an **XComponent** object. This API works only when **type** of the **XComponent** is set to **SURFACE("surface")** or **TEXTURE**. 317 318**Atomic service API**: This API can be used in atomic services since API version 12. 319 320**System capability**: SystemCapability.ArkUI.ArkUI.Full 321 322**Return value** 323 324| Type | Description | 325| ------ | ------------------------------------------------------------ | 326| Object | Context of the **XComponent** object. The APIs contained in the context are defined by developers. The context is passed in as the first parameter of the **onLoad** callback.| 327 328### setXComponentSurfaceRect<sup>12+</sup> 329 330setXComponentSurfaceRect(rect: SurfaceRect): void 331 332Sets the display area for the surface held by the **XComponent**, including the width, height, and position coordinates relative to the upper left corner of the component. This API is only effective when the **XComponent** type is **SURFACE("surface")** or **TEXTURE**. 333 334**Atomic service API**: This API can be used in atomic services since API version 12. 335 336**System capability**: SystemCapability.ArkUI.ArkUI.Full 337 338**Parameters** 339 340| Name| Type | Mandatory| Description | 341| ------ | ------------------------------------ | ---- | --------------------------------- | 342| rect | [SurfaceRect](#surfacerect12) | Yes | Rectangle of the surface held by the **XComponent**.| 343 344> **NOTE** 345> 346> If **offsetX** or **offsetY** in the **rect** parameter is not set, the surface rectangle is centered along the x-axis or y-axis relative to the upper left corner of the **XComponent**. 347> 348> If **surfaceWidth** and **surfaceHeight** in the **rect** parameter are set to **0** or a negative value, this API has no effect. 349> 350> This API has a higher priority than attributes that can change the content offset and size, such as [border](ts-universal-attributes-border.md#border) and [padding](ts-universal-attributes-size.md#padding). 351 352### getXComponentSurfaceRect<sup>12+</sup> 353 354getXComponentSurfaceRect(): SurfaceRect 355 356Obtains the display area for the surface held by the **XComponent**, including the width, height, and position coordinates relative to the upper left corner of the component. This API is only effective when the **XComponent** type is **SURFACE("surface")** or **TEXTURE**. 357 358**Atomic service API**: This API can be used in atomic services since API version 12. 359 360**System capability**: SystemCapability.ArkUI.ArkUI.Full 361 362**Return value** 363 364| Type | Description | 365| ------------------------------------ | ------------------------------------- | 366| [SurfaceRect](#surfacerect12) | Rectangle of the surface held by the **XComponent**.| 367 368### onSurfaceCreated<sup>12+</sup> 369 370onSurfaceCreated(surfaceId: string): void 371 372Triggered when the surface held by the **XComponent** is created. This API works only when **type** of the **XComponent** is set to **SURFACE("surface")** or **TEXTURE**. 373 374**Atomic service API**: This API can be used in atomic services since API version 12. 375 376**System capability**: SystemCapability.ArkUI.ArkUI.Full 377 378**Parameters** 379 380| Name | Type| Mandatory| Description | 381| --------- | -------- | ---- | ------------------------------------------------- | 382| surfaceId | string | Yes | ID of the surface held by the **XComponent**.| 383 384> **NOTE** 385> 386> The callback is triggered only when the **libraryname** parameter is not set for the **XComponent**. 387 388### onSurfaceChanged<sup>12+</sup> 389 390onSurfaceChanged(surfaceId: string, rect: SurfaceRect): void 391 392Triggered when the surface held by the **XComponent** has its size changed (including the time when the **XComponent** is created with the specified size). This API works only when **type** of the **XComponent** is set to **SURFACE** (**"surface"**) or **TEXTURE**. 393 394**Atomic service API**: This API can be used in atomic services since API version 12. 395 396**System capability**: SystemCapability.ArkUI.ArkUI.Full 397 398**Parameters** 399 400| Name | Type | Mandatory| Description | 401| --------- | ------------------------------------- | ---- | ------------------------------------------------------- | 402| surfaceId | string | Yes | ID of the surface held by the **XComponent**. | 403| rect | [SurfaceRect](#surfacerect12) | Yes | Rectangle for displaying the surface held by the **XComponent**.| 404 405> **NOTE** 406> 407> The callback is triggered only when the **libraryname** parameter is not set for the **XComponent**. 408 409### onSurfaceDestroyed<sup>12+</sup> 410 411onSurfaceDestroyed(surfaceId: string): void 412 413Triggered when the surface held by the **XComponent** is destroyed. This API works only when **type** of the **XComponent** is set to **SURFACE** (**"surface"**) or **TEXTURE**. 414 415**Atomic service API**: This API can be used in atomic services since API version 12. 416 417**System capability**: SystemCapability.ArkUI.ArkUI.Full 418 419**Parameters** 420 421| Name | Type| Mandatory| Description | 422| --------- | -------- | ---- | ------------------------------------------------- | 423| surfaceId | string | Yes | ID of the surface held by the **XComponent**.| 424 425> **NOTE** 426> 427> The callback is triggered only when the **libraryname** parameter is not set for the **XComponent**. 428 429### startImageAnalyzer<sup>12+</sup> 430 431startImageAnalyzer(config: ImageAnalyzerConfig): Promise\<void> 432 433Starts AI image analysis in the given settings. Before calling this API, make sure the AI image analyzer is [enabled](#enableanalyzer12).<br>Because the image frame used for analysis is the one captured when this API is called, pay attention to the invoking time of this API.<br>If this API is repeatedly called before the execution is complete, an error callback is triggered. 434 435> **NOTE** 436> 437> The image analysis type cannot be dynamically modified. 438> This API depends on device capabilities. If it is called on an incompatible device, an error code is returned. 439 440**Atomic service API**: This API can be used in atomic services since API version 12. 441 442**System capability**: SystemCapability.ArkUI.ArkUI.Full 443 444**Parameters** 445 446| Name| Type | Mandatory| Description | 447| ------ | --------- | ---- | ---------------------------------------------------------------------- | 448| config | [ImageAnalyzerConfig](ts-image-common.md#imageanalyzerconfig) | Yes | Settings of the AI image analyzer.| 449 450**Return value** 451 452| Type | Description | 453| ----------------- | ------------------------------------ | 454| Promise\<void> | Promise used to return the result.| 455 456**Error codes** 457 458For details about the error codes, see [AI Image Analyzer Error Codes](errorcode-image-analyzer.md). 459 460| ID| Error Message | 461| -------- | -------------------------------------------- | 462| 110001 | Image analysis feature is unsupported. | 463| 110002 | Image analysis is currently being executed. | 464| 110003 | Image analysis is stopped. | 465 466### stopImageAnalyzer<sup>12+</sup> 467 468stopImageAnalyzer(): void 469 470Stops AI image analysis. The content displayed by the AI image analyzer will be destroyed. 471 472> **NOTE** 473> 474> If this API is called when the **startImageAnalyzer** API has not yet returned any result, an error callback is triggered. 475> 476> This feature depends on device capabilities. 477 478**Atomic service API**: This API can be used in atomic services since API version 12. 479 480**System capability**: SystemCapability.ArkUI.ArkUI.Full 481 482### setXComponentSurfaceRotation<sup>12+</sup> 483 484setXComponentSurfaceRotation(rotationOptions: SurfaceRotationOptions): void 485 486Sets whether to lock the orientation of the surface held by this **XComponent** when the screen rotates. This API is effective only when the **XComponent** type is **SURFACE** (**"surface"**). 487 488**Atomic service API**: This API can be used in atomic services since API version 12. 489 490**System capability**: SystemCapability.ArkUI.ArkUI.Full 491 492**Parameters** 493 494| Name| Type | Mandatory| Description | 495| ------ | ------------------------------------ | ---- | --------------------------------- | 496| rotationOptions | [SurfaceRotationOptions](#surfacerotationoptions12) | Yes| Whether to lock the orientation of the surface held by the current **XComponent** when the screen rotates.| 497 498> **NOTE** 499> 500> If **rotationOptions** is not set, the surface held by this **XComponent** rotates with the screen by default. 501> 502> The orientation lock is only applied during the rotation process and is released once the rotation is complete. 503> 504> The setting takes effect only when the screen is rotated by 90°, that is, when it switches between landscape and portrait modes. 505> 506> Make sure the Buffer's width and height remain constant after locking the orientation to prevent distortion. 507 508### getXComponentSurfaceRotation<sup>12+</sup> 509 510getXComponentSurfaceRotation(): Required\<SurfaceRotationOptions> 511 512Obtains whether the orientation of the surface held by this **XComponent** is locked when the screen rotates. This API is effective only when the **XComponent** type is **SURFACE** (**"surface"**). 513 514**Atomic service API**: This API can be used in atomic services since API version 12. 515 516**System capability**: SystemCapability.ArkUI.ArkUI.Full 517 518**Return value** 519 520| Type | Description | 521| ------------------------------------ | ------------------------------------- | 522| Required<[SurfaceRotationOptions](#surfacerotationoptions12)> | Whether the orientation of the surface held by the current **XComponent** is locked when the screen rotates.| 523 524### lockCanvas<sup>20+</sup> 525 526lockCanvas(): DrawingCanvas | null 527 528Obtains a canvas object for drawing content on the **XComponent** component. For details about the drawing methods, see [Canvas](../../apis-arkgraphics2d/arkts-apis-graphics-drawing-Canvas.md). 529 530**Atomic service API**: This API can be used in atomic services since API version 20. 531 532**System capability**: SystemCapability.ArkUI.ArkUI.Full 533 534**Return value** 535| Type | Description | 536| ------------------------------------ | ------------------------------------- | 537| [DrawingCanvas](ts-drawingrenderingcontext.md#drawingcanvas12) \| null | Canvas object for drawing on the **XComponent** area, or **null** if it is unavailable.| 538 539> **NOTE** 540> 541> This API returns **null** if the canvas object cannot be obtained due to the current state of the **XComponent** component. The possible causes are as follows: 542> 543> 1. The surface held by the **XComponent** has not been created yet (you can determine this by setting the [onLoad](#onload) or [onSurfaceCrearted](#onsurfacecreated12) callback, which is triggered after the surface is created). 544> 545> 2. A previous canvas object obtained using **lockCanvas()** has not been released with [unlockCanvasAndPost](#unlockcanvasandpost20). 546> 547> This API is only effective when the **XComponent** type is **TEXTURE** or **SURFACE**. 548> 549> After using this API, do not simultaneously obtain the **NativeWindow** instance on the NDK side and call related APIs for drawing. Doing so may cause buffer contention and context to occur, leading to rendering exceptions such as visual artifacts. 550> 551> This API must be used in conjunction with [unlockCanvasAndPost](#unlockcanvasandpost20). For the implementation example, see [Example 3: Drawing Content on the XComponent Using a Canvas Object](#example-3-drawing-content-on-the-xcomponent-using-a-canvas-object). 552 553### unlockCanvasAndPost<sup>20+</sup> 554 555unlockCanvasAndPost(canvas: DrawingCanvas): void 556 557Submits the drawn content from a canvas object to the display area of the **XComponent** component and releases the canvas object. 558 559**Atomic service API**: This API can be used in atomic services since API version 20. 560 561**System capability**: SystemCapability.ArkUI.ArkUI.Full 562 563**Parameters** 564| Name| Type| Mandatory| Description| 565| -------- | -------- | -------- | -------- | 566| canvas | [DrawingCanvas](ts-drawingrenderingcontext.md#drawingcanvas12) | Yes| Canvas object previously obtained using **lockCanvas()**.| 567 568> **NOTE** 569> 570> 1. Once released using **unlockCanvasAndPost()**, a canvas object becomes immediately unusable. 571> 572> 2. This API is only effective when the **XComponent** type is **TEXTURE** or **SURFACE**. 573> 574> 3. After using this API, do not simultaneously obtain the **NativeWindow** instance on the NDK side and call related APIs for drawing. Doing so may cause buffer contention and context to occur, leading to rendering exceptions such as visual artifacts. 575> 576> 4. This API must be used in conjunction with [lockCanvas](#lockcanvas20). For the implementation example, see [Example 3: Drawing Content on the XComponent Using a Canvas Object](#example-3-drawing-content-on-the-xcomponent-using-a-canvas-object). 577 578## SurfaceRotationOptions<sup>12+</sup> 579 580Defines whether the orientation of the surface held by the current **XComponent** is locked when the screen rotates. 581 582**Atomic service API**: This API can be used in atomic services since API version 12. 583 584**System capability**: SystemCapability.ArkUI.ArkUI.Full 585 586| Name | Type | Read-Only| Optional| Description | 587| ------------- | ------ | ------ | ---- | ------------------------------------------------------------ | 588| lock | boolean | No| Yes | Whether the orientation of the surface is locked when the screen rotates. If this parameter is not set, the default value **false** is used, indicating that the orientation is not locked.<br>**true**: The orientation of the surface is locked when the screen rotates.<br>**false**: The orientation of the surface is not locked when the screen rotates.| 589 590## SurfaceRect<sup>12+</sup> 591 592Describes the rectangle of the surface held by the **XComponent**. 593 594**Atomic service API**: This API can be used in atomic services since API version 12. 595 596**System capability**: SystemCapability.ArkUI.ArkUI.Full 597 598| Name | Type | Read-Only| Optional| Description | 599| ------------- | ------ | ------ | ---- | ------------------------------------------------------------ | 600| offsetX | number | No | Yes | X coordinate of the surface rectangle relative to the upper left corner of the **XComponent**.<br>Unit: px| 601| offsetY | number | No | Yes | Y coordinate of the surface rectangle relative to the upper left corner of the **XComponent**.<br>Unit: px| 602| surfaceWidth | number | No | No | Width of the surface rectangle.<br>Unit: px. | 603| surfaceHeight | number | No | No | Height of the surface rectangle.<br>Unit: px. | 604 605> **NOTE** 606> 607> The **surfaceWidth** and **surfaceHeight** attributes default to the size of the **XComponent** if the [setXComponentSurfaceRect](ts-basic-components-xcomponent.md#setxcomponentsurfacerect12) API is not called and neither [border](ts-universal-attributes-border.md#border) nor [padding](ts-universal-attributes-size.md#padding) is set. 608> 609> Make sure the values of **surfaceWidth** and **surfaceHeight** do not exceed 8192 px. Exceeding this limit may lead to rendering issues. 610> 611> In immersive scenarios, the default layout of **SurfaceRect** does not include the safe area. To achieve an immersive effect, you must set the surface display area using the [setXComponentSurfaceRect](ts-basic-components-xcomponent.md#setxcomponentsurfacerect12) API. 612 613## Example 614 615You can preview how this component looks on a real device, but not in DevEco Studio Previewer. 616 617 618### Example 1: Enabling AI Image Analyzer 619 620This example shows how to use the **enableAnalyzer** attribute to enable AI image analyzer. You can use **XComponentController** to start or stop AI analysis on images. 621 622```ts 623// xxx.ets 624import { BusinessError } from '@kit.BasicServicesKit'; 625import nativeRender from 'libnativerender.so';// Your own .so file implementation (see above for details). 626 627class CustomXComponentController extends XComponentController { 628 onSurfaceCreated(surfaceId: string): void { 629 console.info(`onSurfaceCreated surfaceId: ${surfaceId}`); 630 nativeRender.SetSurfaceId(BigInt(surfaceId)); 631 } 632 633 onSurfaceChanged(surfaceId: string, rect: SurfaceRect): void { 634 console.info(`onSurfaceChanged surfaceId: ${surfaceId}, rect: ${JSON.stringify(rect)}}`); 635 nativeRender.ChangeSurface(BigInt(surfaceId), rect.surfaceWidth, rect.surfaceHeight); 636 } 637 638 onSurfaceDestroyed(surfaceId: string): void { 639 console.info(`onSurfaceDestroyed surfaceId: ${surfaceId}`); 640 nativeRender.DestroySurface(BigInt(surfaceId)); 641 } 642} 643 644@Entry 645@Component 646struct XComponentExample { 647 xComponentController: XComponentController = new CustomXComponentController(); 648 private config: ImageAnalyzerConfig = { 649 types: [ImageAnalyzerType.SUBJECT, ImageAnalyzerType.TEXT] 650 }; 651 private aiController: ImageAnalyzerController = new ImageAnalyzerController(); 652 private options: ImageAIOptions = { 653 types: [ImageAnalyzerType.SUBJECT, ImageAnalyzerType.TEXT], 654 aiController: this.aiController 655 }; 656 @State xcWidth: string = "720px"; 657 @State xcHeight: string = "720px"; 658 @State currentStatus: string = "index"; 659 660 build() { 661 Column({ space: 5 }) { 662 Row() { 663 Text('Native XComponent Sample') 664 .fontSize('24fp') 665 .fontWeight(500) 666 .margin({ 667 left: 24, 668 top: 12 669 }) 670 } 671 .margin({ top: 24 }) 672 .width('100%') 673 .height(56) 674 675 XComponent({ 676 type: XComponentType.SURFACE, 677 controller: this.xComponentController, 678 imageAIOptions: this.options 679 }) 680 .width(this.xcWidth) 681 .height(this.xcHeight) 682 .enableAnalyzer(true) 683 .onClick(() => { 684 let surfaceId = this.xComponentController.getXComponentSurfaceId(); 685 nativeRender.ChangeColor(BigInt(surfaceId)); 686 let hasChangeColor: boolean = false; 687 if (nativeRender.GetXComponentStatus(BigInt(surfaceId))) { 688 hasChangeColor = nativeRender.GetXComponentStatus(BigInt(surfaceId)).hasChangeColor; 689 } 690 if (hasChangeColor) { 691 this.currentStatus = "change color"; 692 } 693 }) 694 Text(this.currentStatus) 695 .fontSize('24fp') 696 .fontWeight(500) 697 Column() { 698 Button('start AI analyze') 699 .onClick(() => { 700 this.xComponentController.startImageAnalyzer(this.config) 701 .then(() => { 702 console.info("analysis complete"); 703 }) 704 .catch((error: BusinessError) => { 705 console.error("error code: " + error.code); 706 }) 707 }) 708 .margin(2) 709 Button('stop AI analyze') 710 .onClick(() => { 711 this.xComponentController.stopImageAnalyzer(); 712 }) 713 .margin(2) 714 Button('get analyzer types') 715 .onClick(() => { 716 this.aiController.getImageAnalyzerSupportTypes(); 717 }) 718 .margin(2) 719 Button('Draw Star') 720 .fontSize('16fp') 721 .fontWeight(500) 722 .margin({ bottom: 24 }) 723 .onClick(() => { 724 let surfaceId = this.xComponentController.getXComponentSurfaceId(); 725 this.xComponentController.getXComponentSurfaceRect(); 726 nativeRender.DrawPattern(BigInt(surfaceId)); 727 let hasDraw: boolean = false; 728 if (nativeRender.GetXComponentStatus(BigInt(surfaceId))) { 729 hasDraw = nativeRender.GetXComponentStatus(BigInt(surfaceId)).hasDraw; 730 } 731 if (hasDraw) { 732 this.currentStatus = "draw star"; 733 } 734 }) 735 .margin(2) 736 }.justifyContent(FlexAlign.Center) 737 } 738 .width("100%") 739 } 740} 741``` 742 743 744 745### Example 2: Locking the Surface Orientation During Screen Rotation 746 747This example shows how to use **setXComponentSurfaceRotation** to lock the surface orientation during screen rotation so that the surface does not rotate with the screen. 748 749```ts 750// xxx.ets 751import nativeRender from 'libnativerender.so'; 752 753class MyXComponentController extends XComponentController { 754 onSurfaceCreated(surfaceId: string): void { 755 console.log(`onSurfaceCreated surfaceId: ${surfaceId}`); 756 nativeRender.SetSurfaceId(BigInt(surfaceId)); 757 } 758 759 onSurfaceChanged(surfaceId: string, rect: SurfaceRect): void { 760 console.log(`onSurfaceChanged surfaceId: ${surfaceId}, rect: ${JSON.stringify(rect)}}`); 761 nativeRender.ChangeSurface(BigInt(surfaceId), rect.surfaceWidth, rect.surfaceHeight); 762 } 763 764 onSurfaceDestroyed(surfaceId: string): void { 765 console.log(`onSurfaceDestroyed surfaceId: ${surfaceId}`); 766 nativeRender.DestroySurface(BigInt(surfaceId)); 767 } 768} 769 770@Entry 771@Component 772struct Index { 773 @State isLock: boolean = true; 774 @State xc_width: number = 500; 775 @State xc_height: number = 700; 776 myXComponentController: XComponentController = new MyXComponentController(); 777 778 build() { 779 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Start }) { 780 XComponent({ 781 id: "XComponent", 782 type: XComponentType.SURFACE, 783 controller: this.myXComponentController 784 }) 785 .onLoad(() => { 786 let surfaceRotation: SurfaceRotationOptions = { lock: this.isLock }; 787 this.myXComponentController.setXComponentSurfaceRotation(surfaceRotation); 788 console.log("Surface getXComponentSurfaceRotation lock = " + 789 this.myXComponentController.getXComponentSurfaceRotation().lock); 790 }) 791 .width(this.xc_width) 792 .height(this.xc_height) 793 Button("Draw") 794 .onClick(() => { 795 let surfaceId = this.myXComponentController.getXComponentSurfaceId(); 796 nativeRender.DrawPattern(BigInt(surfaceId)); 797 }) 798 } 799 } 800} 801``` 802 803### Example 3: Drawing Content on the XComponent Using a Canvas Object 804 805This example shows how to call **lockCanvas** to obtain a canvas object, use the canvas object to call corresponding drawing API, and finally call **unlockCanvasAndPost** to render the content on the **XComponent** component. 806 807```ts 808// xxx.ets 809import { drawing } from '@kit.ArkGraphics2D'; 810 811@Entry 812@Component 813struct Index { 814 private xcController: XComponentController = new XComponentController(); 815 private mCanvas: DrawingCanvas | null = null; 816 817 build() { 818 Column() { 819 XComponent({ type: XComponentType.SURFACE, controller: this.xcController }) 820 .width("80%") 821 .height("80%") 822 .onLoad(() => { 823 this.mCanvas = this.xcController.lockCanvas(); 824 if (this.mCanvas) { 825 this.mCanvas.drawColor(255, 240, 250, 255); // Before each drawing, the entire XComponent area must be fully redrawn; this method can be used to achieve this. 826 const brush = new drawing.Brush(); // Create a brush object. 827 brush.setColor({ // Set the color of the brush. 828 alpha: 255, 829 red: 39, 830 green: 135, 831 blue: 217 832 }); 833 this.mCanvas.attachBrush(brush); // Attach the brush to the canvas. 834 this.mCanvas.drawRect({ // Draw a rectangle. 835 left: 300, 836 right: 800, 837 top: 100, 838 bottom: 800 839 }); 840 this.mCanvas.detachBrush(); // Detach the brush from the canvas. 841 this.xcController.unlockCanvasAndPost(this.mCanvas); 842 } 843 }) 844 } 845 .height('100%') 846 .width('100%') 847 } 848} 849``` 850 851<!--no_check-->