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> You can preview how this component looks on a real device, but not in DevEco Studio Previewer.
12
13
14## Modules to Import
15
16```ts
17import { componentSnapshot } from '@kit.ArkUI';
18```
19
20## componentSnapshot.get
21
22get(id: string, callback: AsyncCallback<image.PixelMap>, options?: SnapshotOptions): void
23
24Obtains the snapshot of a component that has been loaded. This API uses an asynchronous callback to return the result.
25
26> **NOTE** 
27>
28> 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.
29
30**Atomic service API**: This API can be used in atomic services since API version 12.
31
32**System capability**: SystemCapability.ArkUI.ArkUI.Full
33
34**Parameters**
35
36| Name     | Type                                 | Mandatory  | Description                                      |
37| -------- | ----------------------------------- | ---- | ---------------------------------------- |
38| id       | string                              | Yes   | [ID](arkui-ts/ts-universal-attributes-component-id.md) of the target component. |
39| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | Yes   | Callback used to return the result.                              |
40| options<sup>12+</sup>       | [SnapshotOptions](#snapshotoptions12)                              | No   | Custom settings of the snapshot. |
41
42**Error codes** 
43
44For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
45
46| ID | Error Message           |
47| -------- | ------------------- |
48| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
49| 100001   | Invalid ID. |
50
51**Example**
52
53```ts
54import { componentSnapshot } from '@kit.ArkUI';
55import { image } from '@kit.ImageKit';
56
57@Entry
58@Component
59struct SnapshotExample {
60  @State pixmap: image.PixelMap | undefined = undefined
61
62  build() {
63    Column() {
64      Row() {
65        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
66        Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root")
67      }
68      Button("click to generate UI snapshot")
69        .onClick(() => {
70          componentSnapshot.get("root", (error: Error, pixmap: image.PixelMap) => {
71            if (error) {
72              console.log("error: " + JSON.stringify(error))
73              return;
74            }
75            this.pixmap = pixmap
76          }, {scale : 2, waitUntilRenderFinished : true})
77        }).margin(10)
78    }
79    .width('100%')
80    .height('100%')
81    .alignItems(HorizontalAlign.Center)
82  }
83}
84```
85
86![componentget](figures/componentget.gif) 
87
88## componentSnapshot.get
89
90get(id: string, options?: SnapshotOptions): Promise<image.PixelMap>
91
92Obtains the snapshot of a component that has been loaded. This API uses a promise to return the result.
93
94> **NOTE**
95>
96> 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.
97
98**Atomic service API**: This API can be used in atomic services since API version 12.
99
100**System capability**: SystemCapability.ArkUI.ArkUI.Full
101
102**Parameters**
103
104| Name | Type    | Mandatory  | Description                                      |
105| ---- | ------ | ---- | ---------------------------------------- |
106| id   | string | Yes   | [ID](arkui-ts/ts-universal-attributes-component-id.md) of the target component. |
107| options<sup>12+</sup>       | [SnapshotOptions](#snapshotoptions12)                              | No   | Custom settings of the snapshot. |
108
109**Return value**
110
111| Type                           | Description      |
112| ----------------------------- | -------- |
113| Promise&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | Promise used to return the result. |
114
115**Error codes** 
116
117For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
118
119| ID | Error Message               |
120| ------ | ------------------- |
121| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
122| 100001 | Invalid ID. |
123
124**Example**
125
126```ts
127import { componentSnapshot } from '@kit.ArkUI';
128import { image } from '@kit.ImageKit';
129
130@Entry
131@Component
132struct SnapshotExample {
133  @State pixmap: image.PixelMap | undefined = undefined
134
135  build() {
136    Column() {
137      Row() {
138        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
139        Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root")
140      }
141      Button("click to generate UI snapshot")
142        .onClick(() => {
143          componentSnapshot.get("root", {scale : 2, waitUntilRenderFinished : true})
144            .then((pixmap: image.PixelMap) => {
145              this.pixmap = pixmap
146            }).catch((err:Error) => {
147            console.log("error: " + err)
148          })
149        }).margin(10)
150    }
151    .width('100%')
152    .height('100%')
153    .alignItems(HorizontalAlign.Center)
154  }
155}
156```
157
158![componentget](figures/componentget.gif) 
159
160## componentSnapshot.createFromBuilder
161
162createFromBuilder(builder: CustomBuilder, callback: AsyncCallback<image.PixelMap>, delay?: number, checkImageStatus?: boolean, options?: SnapshotOptions): void
163
164Renders 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.
165
166> **NOTE** 
167>
168> 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.
169>
170> 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.
171
172**Atomic service API**: This API can be used in atomic services since API version 12.
173
174**System capability**: SystemCapability.ArkUI.ArkUI.Full
175
176**Parameters**
177
178| Name     | Type                                      | Mandatory  | Description        |
179| -------- | ---------------------------------------- | ---- | ---------- |
180| builder  | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | Yes   | Builder of the custom component.<br>**NOTE**<br>The global builder is not supported.|
181| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt;      | Yes   | Callback used to return the result. The coordinates and size of the offscreen component's drawing area can be obtained through the callback. |
182| 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|
183| 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**|
184| options<sup>12+</sup>       | [SnapshotOptions](#snapshotoptions12)           | No   | Custom settings of the snapshot. |
185
186**Error codes** 
187
188For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
189
190| ID | Error Message                                 |
191| -------- | ----------------------------------------- |
192| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
193| 100001   | The builder is not a valid build function. |
194| 160001 | The image component in builder failed to load. |
195
196**Example**
197
198```ts
199import { componentSnapshot, componentUtils } from '@kit.ArkUI';
200import { image } from '@kit.ImageKit';
201
202@Entry
203@Component
204struct OffscreenSnapshotExample {
205  @State pixmap: image.PixelMap | undefined = undefined
206
207  @Builder
208  RandomBuilder() {
209    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
210      Text('Test menu item 1')
211        .fontSize(20)
212        .width(100)
213        .height(50)
214        .textAlign(TextAlign.Center)
215      Divider().height(10)
216      Text('Test menu item 2')
217        .fontSize(20)
218        .width(100)
219        .height(50)
220        .textAlign(TextAlign.Center)
221    }
222    .width(100)
223    .id("builder")
224  }
225
226  build() {
227    Column() {
228      Button("click to generate offscreen UI snapshot")
229        .onClick(() => {
230          componentSnapshot.createFromBuilder(()=>{this.RandomBuilder()},
231            (error: Error, pixmap: image.PixelMap) => {
232              if(error){
233                console.log("error: " + JSON.stringify(error))
234                return;
235              }
236              this.pixmap = pixmap
237              // save pixmap to file
238              // ....
239              // get component size and location
240              let info = componentUtils.getRectangleById("builder")
241              console.log(info.size.width + ' ' + info.size.height + ' ' + info.localOffset.x + ' ' + info.localOffset.y + ' ' + info.windowOffset.x + ' ' + info.windowOffset.y)
242            }, 320, true, {scale : 2, waitUntilRenderFinished : true})
243        })
244      Image(this.pixmap)
245        .margin(10)
246        .height(200)
247        .width(200)
248        .border({ color: Color.Black, width: 2 })
249    }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
250  }
251}
252```
253
254![componentcreate](figures/componentcreate.gif) 
255
256## componentSnapshot.createFromBuilder
257
258createFromBuilder(builder: CustomBuilder, delay?: number, checkImageStatus?: boolean, options?: SnapshotOptions): Promise<image.PixelMap>
259
260Renders 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.
261
262> **NOTE** 
263>
264> 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.
265>
266> 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.
267
268**Atomic service API**: This API can be used in atomic services since API version 12.
269
270**System capability**: SystemCapability.ArkUI.ArkUI.Full
271
272**Parameters**
273
274| Name    | Type                                      | Mandatory  | Description        |
275| ------- | ---------------------------------------- | ---- | ---------- |
276| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | Yes   | Builder of the custom component.<br>**NOTE**<br>The global builder is not supported. |
277| 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|
278| 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**|
279| options<sup>12+</sup>       | [SnapshotOptions](#snapshotoptions12)           | No   | Custom settings of the snapshot. |
280
281**Return value**
282
283| Type                           | Description      |
284| ----------------------------- | -------- |
285| Promise&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | Promise used to return the result. |
286
287**Error codes** 
288For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
289
290| ID | Error Message                                    |
291| ------ | ---------------------------------------- |
292| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
293| 100001 | The builder is not a valid build function. |
294| 160001 | The image component in builder failed to load. |
295
296**Example**
297
298```ts
299import { componentSnapshot, componentUtils } from '@kit.ArkUI'
300import { image } from '@kit.ImageKit'
301
302@Entry
303@Component
304struct OffscreenSnapshotExample {
305  @State pixmap: image.PixelMap | undefined = undefined
306
307  @Builder
308  RandomBuilder() {
309    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
310      Text('Test menu item 1')
311        .fontSize(20)
312        .width(100)
313        .height(50)
314        .textAlign(TextAlign.Center)
315      Divider().height(10)
316      Text('Test menu item 2')
317        .fontSize(20)
318        .width(100)
319        .height(50)
320        .textAlign(TextAlign.Center)
321    }
322    .width(100)
323    .id("builder")
324  }
325
326  build() {
327    Column() {
328      Button("click to generate offscreen UI snapshot")
329        .onClick(() => {
330          componentSnapshot.createFromBuilder(()=>{this.RandomBuilder()}, 320, true, {scale : 2, waitUntilRenderFinished : true})
331            .then((pixmap: image.PixelMap) => {
332              this.pixmap = pixmap
333              // save pixmap to file
334              // ....
335              // get component size and location
336              let info = componentUtils.getRectangleById("builder")
337              console.log(info.size.width + ' ' + info.size.height + ' ' + info.localOffset.x + ' ' + info.localOffset.y + ' ' + info.windowOffset.x + ' ' + info.windowOffset.y)
338            }).catch((err:Error) => {
339            console.log("error: " + err)
340          })
341        })
342      Image(this.pixmap)
343        .margin(10)
344        .height(200)
345        .width(200)
346        .border({ color: Color.Black, width: 2 })
347    }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
348  }
349}
350```
351
352![componentcreate](figures/componentcreate.gif) 
353
354## SnapshotOptions<sup>12+</sup>
355
356**System capability**: SystemCapability.ArkUI.ArkUI.Full
357
358**Atomic service API**: This API can be used in atomic services since API version 12.
359
360| Name          | Type            | Mandatory          | Description                        |
361| ---------------|------------     | -----------------------------| -----------------------------|
362| scale           | number | No | Scale ratio for rendering pixel maps during a snapshot. Note that a scale ratio too high may slow down the snapshot process, and even result in a snapshot failure.<br> Default value: **1**   |
363| 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**        |
364