1# @ohos.arkui.componentSnapshot (Component Snapshot) 2 3The **componentSnapshot** module provides APIs for obtaining component snapshots, including snapshots of components that have been loaded and snapshots of components that have not been loaded yet. Note that a component snapshot does not contain content drawn outside the area of the owning component or the parent component. If sibling nodes are stacked in the component area, they are not displayed in the screenshot. 4 5> **NOTE** 6> 7> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. 8> 9>In scenarios where [XComponent](arkui-ts/ts-basic-components-xcomponent.md) is used to, for example, display video or camera streams, obtain images through [surface](../apis-image-kit/js-apis-image.md#imagecreatepixelmapfromsurface11), instead of through an API in this module. 10> 11>If the content of a component does not fill the entire area allocated for it, any remaining space in the snapshot will be rendered as transparent pixels. In addition, if the component uses [image effects](arkui-ts/ts-universal-attributes-image-effect.md) or other effect-related attributes, the resulting snapshot may not be as expected. To address these potential issues, check whether to fill the component's transparent content area or to use an alternative method such as taking a [window screenshot](js-apis-window.md#snapshot9). 12> 13> You can preview how this component looks on a real device, but not in DevEco Studio Previewer. 14 15 16## Modules to Import 17 18```ts 19import { componentSnapshot } from '@kit.ArkUI'; 20``` 21 22## componentSnapshot.get 23 24get(id: string, callback: AsyncCallback<image.PixelMap>, options?: SnapshotOptions): void 25 26Obtains the snapshot of a component that has been loaded. This API uses an asynchronous callback to return the result. 27 28> **NOTE** 29> 30> The snapshot captures content rendered in the last frame. If this API is called when the component triggers an update, the re-rendered content will not be included in the obtained snapshot. 31 32**Atomic service API**: This API can be used in atomic services since API version 12. 33 34**System capability**: SystemCapability.ArkUI.ArkUI.Full 35 36**Parameters** 37 38| Name | Type | Mandatory | Description | 39| -------- | ----------------------------------- | ---- | ---------------------------------------- | 40| id | string | Yes | [ID](arkui-ts/ts-universal-attributes-component-id.md) of the target component.| 41| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | Yes | Callback used to return the result. | 42| options<sup>12+</sup> | [SnapshotOptions](#snapshotoptions12) | No | Custom settings of the snapshot.| 43 44**Error codes** 45 46For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 47 48| ID| Error Message | 49| -------- | ------------------- | 50| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 51| 100001 | Invalid ID. | 52 53**Example** 54 55> **NOTE** 56> 57> To avoid confusion with **componentSnapshot** instances, it is recommended that you obtain a **UIContext** instance using the [getUIContext](js-apis-arkui-UIContext.md#uicontext) API, and then obtain the **componentSnapshot** instance bound to the context through the [getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12) API. 58 59```ts 60import { componentSnapshot } from '@kit.ArkUI'; 61import { image } from '@kit.ImageKit'; 62 63@Entry 64@Component 65struct SnapshotExample { 66 @State pixmap: image.PixelMap | undefined = undefined 67 68 build() { 69 Column() { 70 Row() { 71 Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5) 72 Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root") 73 } 74 Button("click to generate UI snapshot") 75 .onClick(() => { 76 // You are advised to use this.getUIContext().getComponentSnapshot().get(). 77 componentSnapshot.get("root", (error: Error, pixmap: image.PixelMap) => { 78 if (error) { 79 console.log("error: " + JSON.stringify(error)) 80 return; 81 } 82 this.pixmap = pixmap 83 }, {scale : 2, waitUntilRenderFinished : true}) 84 }).margin(10) 85 } 86 .width('100%') 87 .height('100%') 88 .alignItems(HorizontalAlign.Center) 89 } 90} 91``` 92 93 94 95## componentSnapshot.get 96 97get(id: string, options?: SnapshotOptions): Promise<image.PixelMap> 98 99Obtains the snapshot of a component that has been loaded. This API uses a promise to return the result. 100 101> **NOTE** 102> 103> The snapshot captures content rendered in the last frame. If this API is called when the component triggers an update, the re-rendered content will not be included in the obtained snapshot. 104 105**Atomic service API**: This API can be used in atomic services since API version 12. 106 107**System capability**: SystemCapability.ArkUI.ArkUI.Full 108 109**Parameters** 110 111| Name | Type | Mandatory | Description | 112| ---- | ------ | ---- | ---------------------------------------- | 113| id | string | Yes | [ID](arkui-ts/ts-universal-attributes-component-id.md) of the target component.| 114| options<sup>12+</sup> | [SnapshotOptions](#snapshotoptions12) | No | Custom settings of the snapshot.| 115 116**Return value** 117 118| Type | Description | 119| ----------------------------- | -------- | 120| Promise<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | Promise used to return the result.| 121 122**Error codes** 123 124For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 125 126| ID | Error Message | 127| ------ | ------------------- | 128| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 129| 100001 | Invalid ID. | 130 131**Example** 132 133> **NOTE** 134> 135> To avoid confusion with **componentSnapshot** instances, it is recommended that you obtain a **UIContext** instance using the [getUIContext](js-apis-arkui-UIContext.md#uicontext) API, and then obtain the **componentSnapshot** instance bound to the context through the [getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12) API. 136 137```ts 138import { componentSnapshot } from '@kit.ArkUI'; 139import { image } from '@kit.ImageKit'; 140 141@Entry 142@Component 143struct SnapshotExample { 144 @State pixmap: image.PixelMap | undefined = undefined 145 146 build() { 147 Column() { 148 Row() { 149 Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5) 150 Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root") 151 } 152 Button("click to generate UI snapshot") 153 .onClick(() => { 154 // You are advised to use this.getUIContext().getComponentSnapshot().get(). 155 componentSnapshot.get("root", {scale : 2, waitUntilRenderFinished : true}) 156 .then((pixmap: image.PixelMap) => { 157 this.pixmap = pixmap 158 }).catch((err:Error) => { 159 console.log("error: " + err) 160 }) 161 }).margin(10) 162 } 163 .width('100%') 164 .height('100%') 165 .alignItems(HorizontalAlign.Center) 166 } 167} 168``` 169 170 171 172## componentSnapshot.createFromBuilder 173 174createFromBuilder(builder: CustomBuilder, callback: AsyncCallback<image.PixelMap>, delay?: number, checkImageStatus?: boolean, options?: SnapshotOptions): void 175 176Renders a custom component in the application background and outputs its snapshot. This API uses an asynchronous callback to return the result. The coordinates and size of the offscreen component's drawing area can be obtained through the callback. 177 178> **NOTE** 179> 180> To account for the time spent in awaiting component building and rendering, the callback of offscreen snapshots has a delay of less than 500 ms. 181> 182> Components in the builder do not support the setting of animation-related attributes, such as [transition](arkui-ts/ts-transition-animation-component.md). 183> 184> If a component is on a time-consuming task, for example, an [Image](arkui-ts/ts-basic-components-image.md) or [Web](../apis-arkweb/ts-basic-components-web.md) component that is loading online images, its loading may be still in progress when this API is called. In this case, the output snapshot does not represent the component in the way it looks when the loading is successfully completed. 185 186**Atomic service API**: This API can be used in atomic services since API version 12. 187 188**System capability**: SystemCapability.ArkUI.ArkUI.Full 189 190**Parameters** 191 192| Name | Type | Mandatory | Description | 193| -------- | ---------------------------------------- | ---- | ---------- | 194| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | Yes | Builder of the custom component.<br>**NOTE**<br>The global builder is not supported.| 195| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | Yes | Callback used to return the result. The coordinates and size of the offscreen component's drawing area can be obtained through the callback.| 196| delay<sup>12+</sup> | number | No | Delay time for triggering the screenshot command. When the layout includes an image component, it is necessary to set a delay time to allow the system to decode the image resources. The decoding time is subject to the resource size. In light of this, whenever possible, use pixel map resources that do not require decoding.<br> When pixel map resources are used or when **syncload** to **true** for the **Image** component, you can set **delay** to **0** to forcibly capture snapshots without waiting. This delay time does not refer to the time from the API call to the return: As the system needs to temporarily construct the passed-in **builder** offscreen, the return time is usually longer than this delay.<br>**NOTE**<br>In the **builder** passed in, state variables should not be used to control the construction of child components. If they are used, they should not change when the API is called, so as to avoid unexpected snapshot results.<br> Default value: **300**<br> Unit: ms| 197| checkImageStatus<sup>12+</sup> | boolean | No | Whether to check the image decoding status before taking a snapshot. If the value is **true**, the system checks whether all **Image** components have been decoded before taking the snapshot. If the check is not completed, the system aborts the snapshot and returns an exception.<br>Default value: **false**| 198| options<sup>12+</sup> | [SnapshotOptions](#snapshotoptions12) | No | Custom settings of the snapshot.| 199 200**Error codes** 201 202For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 203 204| ID| Error Message | 205| -------- | ------------------------------------------------------------ | 206| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 207| 100001 | The builder is not a valid build function. | 208| 160001 | An image component in builder is not ready for taking a snapshot. The check for the ready state is required when the checkImageStatus option is enabled. | 209 210**Example** 211 212> **NOTE** 213> 214> To avoid confusion with **componentSnapshot** instances, it is recommended that you obtain a **UIContext** instance using the [getUIContext](js-apis-arkui-UIContext.md#uicontext) API, and then obtain the **componentSnapshot** instance bound to the context through the [getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12) API. 215 216```ts 217import { componentSnapshot } from '@kit.ArkUI'; 218import { image } from '@kit.ImageKit'; 219 220@Entry 221@Component 222struct OffscreenSnapshotExample { 223 @State pixmap: image.PixelMap | undefined = undefined 224 225 @Builder 226 RandomBuilder() { 227 Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { 228 Text('Test menu item 1') 229 .fontSize(20) 230 .width(100) 231 .height(50) 232 .textAlign(TextAlign.Center) 233 Divider().height(10) 234 Text('Test menu item 2') 235 .fontSize(20) 236 .width(100) 237 .height(50) 238 .textAlign(TextAlign.Center) 239 } 240 .width(100) 241 .id("builder") 242 } 243 244 build() { 245 Column() { 246 Button("click to generate offscreen UI snapshot") 247 .onClick(() => { 248 // You are advised to use this.getUIContext().getComponentSnapshot().createFromBuilder(). 249 componentSnapshot.createFromBuilder(()=>{this.RandomBuilder()}, 250 (error: Error, pixmap: image.PixelMap) => { 251 if(error){ 252 console.log("error: " + JSON.stringify(error)) 253 return; 254 } 255 this.pixmap = pixmap 256 // save pixmap to file 257 // .... 258 // get component size and location 259 let info = this.getUIContext().getComponentUtils().getRectangleById("builder") 260 console.log(info.size.width + ' ' + info.size.height + ' ' + info.localOffset.x + ' ' + info.localOffset.y + ' ' + info.windowOffset.x + ' ' + info.windowOffset.y) 261 }, 320, true, {scale : 2, waitUntilRenderFinished : true}) 262 }) 263 Image(this.pixmap) 264 .margin(10) 265 .height(200) 266 .width(200) 267 .border({ color: Color.Black, width: 2 }) 268 }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300) 269 } 270} 271``` 272 273 274 275## componentSnapshot.createFromBuilder 276 277createFromBuilder(builder: CustomBuilder, delay?: number, checkImageStatus?: boolean, options?: SnapshotOptions): Promise<image.PixelMap> 278 279Renders a custom component in the application background and outputs its snapshot. This API uses a promise to return the result. The coordinates and size of the offscreen component's drawing area can be obtained through the callback. 280 281> **NOTE** 282> 283> To account for the time spent in awaiting component building and rendering, the callback of offscreen snapshots has a delay of less than 500 ms. 284> 285> Components in the builder do not support the setting of animation-related attributes, such as [transition](arkui-ts/ts-transition-animation-component.md). 286> 287> If a component is on a time-consuming task, for example, an [Image](arkui-ts/ts-basic-components-image.md) or [Web](../apis-arkweb/ts-basic-components-web.md) component that is loading online images, its loading may be still in progress when this API is called. In this case, the output snapshot does not represent the component in the way it looks when the loading is successfully completed. 288 289**Atomic service API**: This API can be used in atomic services since API version 12. 290 291**System capability**: SystemCapability.ArkUI.ArkUI.Full 292 293**Parameters** 294 295| Name | Type | Mandatory | Description | 296| ------- | ---------------------------------------- | ---- | ---------- | 297| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | Yes | Builder of the custom component.<br>**NOTE**<br>The global builder is not supported.| 298| delay<sup>12+</sup> | number | No | Delay time for triggering the screenshot command. When the layout includes an image component, it is necessary to set a delay time to allow the system to decode the image resources. The decoding time is subject to the resource size. In light of this, whenever possible, use pixel map resources that do not require decoding.<br> When pixel map resources are used or when **syncload** to **true** for the **Image** component, you can set **delay** to **0** to forcibly capture snapshots without waiting. This delay time does not refer to the time from the API call to the return: As the system needs to temporarily construct the passed-in **builder** offscreen, the return time is usually longer than this delay.<br>**NOTE**<br>In the **builder** passed in, state variables should not be used to control the construction of child components. If they are used, they should not change when the API is called, so as to avoid unexpected snapshot results.<br> Default value: **300**<br> Unit: ms| 299| checkImageStatus<sup>12+</sup> | boolean | No | Whether to check the image decoding status before taking a snapshot. If the value is **true**, the system checks whether all **Image** components have been decoded before taking the snapshot. If the check is not completed, the system aborts the snapshot and returns an exception.<br>Default value: **false**| 300| options<sup>12+</sup> | [SnapshotOptions](#snapshotoptions12) | No | Custom settings of the snapshot.| 301 302**Return value** 303 304| Type | Description | 305| ----------------------------- | -------- | 306| Promise<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | Promise used to return the result.| 307 308**Error codes** 309For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 310 311| ID | Error Message | 312| ------ | ---------------------------------------- | 313| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 314| 100001 | The builder is not a valid build function. | 315| 160001 | An image component in builder is not ready for taking a snapshot. The check for the ready state is required when the checkImageStatus option is enabled. | 316 317**Example** 318 319> **NOTE** 320> 321> To avoid confusion with **componentSnapshot** instances, it is recommended that you obtain a **UIContext** instance using the [getUIContext](js-apis-arkui-UIContext.md#uicontext) API, and then obtain the **componentSnapshot** instance bound to the context through the [getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12) API. 322 323```ts 324import { componentSnapshot } from '@kit.ArkUI' 325import { image } from '@kit.ImageKit' 326 327@Entry 328@Component 329struct OffscreenSnapshotExample { 330 @State pixmap: image.PixelMap | undefined = undefined 331 332 @Builder 333 RandomBuilder() { 334 Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { 335 Text('Test menu item 1') 336 .fontSize(20) 337 .width(100) 338 .height(50) 339 .textAlign(TextAlign.Center) 340 Divider().height(10) 341 Text('Test menu item 2') 342 .fontSize(20) 343 .width(100) 344 .height(50) 345 .textAlign(TextAlign.Center) 346 } 347 .width(100) 348 .id("builder") 349 } 350 351 build() { 352 Column() { 353 Button("click to generate offscreen UI snapshot") 354 .onClick(() => { 355 // You are advised to use this.getUIContext().getComponentSnapshot().createFromBuilder(). 356 componentSnapshot.createFromBuilder(()=>{this.RandomBuilder()}, 320, true, {scale : 2, waitUntilRenderFinished : true}) 357 .then((pixmap: image.PixelMap) => { 358 this.pixmap = pixmap 359 // save pixmap to file 360 // .... 361 // get component size and location 362 let info = this.getUIContext().getComponentUtils().getRectangleById("builder") 363 console.log(info.size.width + ' ' + info.size.height + ' ' + info.localOffset.x + ' ' + info.localOffset.y + ' ' + info.windowOffset.x + ' ' + info.windowOffset.y) 364 }).catch((err:Error) => { 365 console.log("error: " + err) 366 }) 367 }) 368 Image(this.pixmap) 369 .margin(10) 370 .height(200) 371 .width(200) 372 .border({ color: Color.Black, width: 2 }) 373 }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300) 374 } 375} 376``` 377 378 379 380## componentSnapshot.getSync<sup>12+</sup> 381 382getSync(id: string, options?: SnapshotOptions): image.PixelMap 383 384Obtains the snapshot of a component that has been loaded. This API synchronously waits for the snapshot to complete and returns a [PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) object. 385 386> **NOTE** 387> 388> The snapshot captures content rendered in the last frame. If this API is called when the component triggers an update, the re-rendered content will not be included in the obtained snapshot. 389 390**Atomic service API**: This API can be used in atomic services since API version 12. 391 392**System capability**: SystemCapability.ArkUI.ArkUI.Full 393 394**Parameters** 395 396| Name | Type | Mandatory | Description | 397| ---- | ------ | ---- | ---------------------------------------- | 398| id | string | Yes | [ID](arkui-ts/ts-universal-attributes-component-id.md) of the target component.| 399| options | [SnapshotOptions](#snapshotoptions12) | No | Custom settings of the snapshot.| 400 401**Return value** 402 403| Type | Description | 404| ----------------------------- | -------- | 405| image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Promise used to return the result.| 406 407**Error codes** 408 409For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 410 411| ID | Error Message | 412| ------ | ------------------- | 413| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 414| 100001 | Invalid ID. | 415| 160002 | Timeout. | 416 417**Example** 418 419> **NOTE** 420> 421> To avoid confusion with **componentSnapshot** instances, it is recommended that you obtain a **UIContext** instance using the [getUIContext](js-apis-arkui-UIContext.md#uicontext) API, and then obtain the **componentSnapshot** instance bound to the context through the [getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12) API. 422 423```ts 424import { componentSnapshot } from '@kit.ArkUI'; 425import { image } from '@kit.ImageKit'; 426 427@Entry 428@Component 429struct SnapshotExample { 430 @State pixmap: image.PixelMap | undefined = undefined 431 432 build() { 433 Column() { 434 Row() { 435 Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5) 436 Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root") 437 } 438 Button("click to generate UI snapshot") 439 .onClick(() => { 440 try { 441 // You are advised to use this.getUIContext().getComponentSnapshot().getSync(). 442 let pixelmap = componentSnapshot.getSync("root", {scale : 2, waitUntilRenderFinished : true}) 443 this.pixmap = pixelmap 444 } catch (error) { 445 console.error("getSync errorCode: " + error.code + " message: " + error.message) 446 } 447 }).margin(10) 448 } 449 .width('100%') 450 .height('100%') 451 .alignItems(HorizontalAlign.Center) 452 } 453} 454``` 455 456 457 458## SnapshotOptions<sup>12+</sup> 459 460**System capability**: SystemCapability.ArkUI.ArkUI.Full 461 462**Atomic service API**: This API can be used in atomic services since API version 12. 463 464| Name | Type | Mandatory | Description | 465| ---------------|------------ | -----------------------------| -----------------------------| 466| scale | number | No| Scale ratio for rendering pixel maps during a snapshot. Note that a high scale ratio may increase the time taken for the snapshot or even result in a snapshot failure.<br> Default value: **1**<br>**NOTE**<br>Avoid capturing images that are excessively large, ideally not larger than the screen size. If the dimensions of the image to capture exceed device-specific underlying limits, the snapshot will fail. | 467| waitUntilRenderFinished | boolean | No| Whether to enforce waiting for all rendering commands to complete before the system takes the snapshot. This option can ensure that the content of the snapshot is in the most up-to-date state and should be enabled whenever possible. However, it's important to note that enabling this option may result in a longer response time from the API. The specific duration depends on the amount of redraw area required by the page at that particular moment.<br> Default value: **false** | 468