• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
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](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 the DevEco Studio Previewer.
12
13
14## Modules to Import
15
16```ts
17import componentSnapshot from "@ohos.arkui.componentSnapshot";
18```
19
20## componentSnapshot.get
21
22get(id: string, callback: AsyncCallback<image.PixelMap>): 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**System capability**: SystemCapability.ArkUI.ArkUI.Full
31
32**Parameters**
33
34| Name     | Type                                 | Mandatory  | Description                                      |
35| -------- | ----------------------------------- | ---- | ---------------------------------------- |
36| id       | string                              | Yes   | [ID](../arkui-ts/ts-universal-attributes-component-id.md) of the target component.|
37| callback | [AsyncCallback](js-apis-base.md#asynccallback)&lt;image.[PixelMap](js-apis-image.md#pixelmap7)&gt; | Yes   | Callback used to return the result.                              |
38
39**Error codes**
40
41| ID| Error Message           |
42| -------- | ------------------- |
43| 100001   | if id is not valid. |
44
45**Example**
46
47```ts
48import componentSnapshot from '@ohos.arkui.componentSnapshot'
49import image from '@ohos.multimedia.image'
50
51@Entry
52@Component
53struct SnapshotExample {
54  @State pixmap: image.PixelMap|undefined = undefined
55
56  build() {
57    Column() {
58      Image(this.pixmap)
59        .width(300).height(300)
60      // ...Component
61      // ...Component
62      // ...Component
63      Button("click to generate UI snapshot")
64        .onClick(() => {
65          componentSnapshot.get("root", (error: Error, pixmap: image.PixelMap) => {
66                if(error){
67                  console.log("error: " + JSON.stringify(error))
68                  return;
69                }
70                this.pixmap = pixmap
71                // save pixmap to file
72                // ....
73             })
74        })
75    }
76    .width('80%')
77    .margin({ left: 10, top: 5, bottom: 5 })
78    .height(200)
79    .border({ color: '#880606', width: 2 })
80    .id("root")
81  }
82}
83```
84
85## componentSnapshot.get
86
87get(id: string): Promise<image.PixelMap>
88
89Obtains the snapshot of a component that has been loaded. This API uses a promise to return the result.
90
91> **NOTE**
92>
93> 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.
94
95**System capability**: SystemCapability.ArkUI.ArkUI.Full
96
97**Parameters**
98
99| Name | Type    | Mandatory  | Description                                      |
100| ---- | ------ | ---- | ---------------------------------------- |
101| id   | string | Yes   | [ID](../arkui-ts/ts-universal-attributes-component-id.md) of the target component.|
102
103**Return value**
104
105| Type                           | Description      |
106| ----------------------------- | -------- |
107| Promise&lt;image.[PixelMap](js-apis-image.md#pixelmap7)&gt; | Promise used to return the result.|
108
109**Error codes**
110
111| ID | Error Message               |
112| ------ | ------------------- |
113| 100001 | if id is not valid. |
114
115**Example**
116
117```ts
118import componentSnapshot from '@ohos.arkui.componentSnapshot'
119import image from '@ohos.multimedia.image'
120
121@Entry
122@Component
123struct SnapshotExample {
124  @State pixmap: image.PixelMap|undefined = undefined
125
126  build() {
127    Column() {
128      Image(this.pixmap)
129        .width(300).height(300)
130      // ...Component
131      // ...Component
132      // ...Component
133      Button("click to generate UI snapshot")
134        .onClick(() => {
135          componentSnapshot.get("root")
136            .then((pixmap: image.PixelMap) => {
137              this.pixmap = pixmap
138              // save pixmap to file
139              // ....
140            }).catch((err:Error) => {
141            console.log("error: " + err)
142          })
143        })
144    }
145    .width('80%')
146    .margin({ left: 10, top: 5, bottom: 5 })
147    .height(200)
148    .border({ color: '#880606', width: 2 })
149    .id("root")
150  }
151}
152```
153
154## componentSnapshot.createFromBuilder
155
156createFromBuilder(builder: CustomBuilder, callback: AsyncCallback<image.PixelMap>): void
157
158Renders 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.
159
160> **NOTE**
161>
162> 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.
163>
164> If a component is on a time-consuming task, for example, an [\<Image>](../arkui-ts/ts-basic-components-image.md) or [\<Web>](../arkui-ts/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.
165
166
167**System capability**: SystemCapability.ArkUI.ArkUI.Full
168
169**Parameters**
170
171| Name     | Type                                      | Mandatory  | Description        |
172| -------- | ---------------------------------------- | ---- | ---------- |
173| builder  | [CustomBuilder](../arkui-ts/ts-types.md#custombuilder8) | Yes   | Builder of the custom component.<br>**NOTE**<br>The global builder is not supported.|
174| callback | [AsyncCallback](js-apis-base.md#asynccallback)&lt;image.[PixelMap](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.|
175
176**Error codes**
177
178| ID| Error Message                                 |
179| -------- | ----------------------------------------- |
180| 100001   | if builder is not a valid build function. |
181
182**Example**
183
184```ts
185import componentSnapshot from '@ohos.arkui.componentSnapshot'
186import image from '@ohos.multimedia.image'
187import componentUtils from '@ohos.arkui.componentUtils'
188
189@Entry
190@Component
191struct OffscreenSnapshotExample {
192  @State pixmap: image.PixelMap | undefined = undefined
193
194  @Builder
195  RandomBuilder() {
196    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
197      Text('Test menu item 1')
198        .fontSize(20)
199        .width(100)
200        .height(50)
201        .textAlign(TextAlign.Center)
202      Divider().height(10)
203      Text('Test menu item 2')
204        .fontSize(20)
205        .width(100)
206        .height(50)
207        .textAlign(TextAlign.Center)
208    }
209    .width(100)
210    .id("builder")
211  }
212
213  build() {
214    Column() {
215      Button("click to generate offscreen UI snapshot")
216        .onClick(() => {
217          componentSnapshot.createFromBuilder(()=>{this.RandomBuilder()},
218            (error: Error, pixmap: image.PixelMap) => {
219              if(error){
220                  console.log("error: " + JSON.stringify(error))
221                  return;
222              }
223              this.pixmap = pixmap
224              // save pixmap to file
225              // ....
226              // get component size and location
227              let info = componentUtils.getRectangleById("builder")
228              console.log(info.size.width + ' ' + info.size.height + ' ' + info.localOffset.x + ' ' + info.localOffset.y + ' ' + info.windowOffset.x + ' ' + info.windowOffset.y)
229            })
230        })
231      Image(this.pixmap)
232        .margin(10)
233        .height(100)
234        .width(100)
235    }.width('80%').margin({ left: 10, top: 5, bottom: 5 }).height(200)
236    .border({ color: '#880606', width: 2 })
237  }
238}
239```
240
241## componentSnapshot.createFromBuilder
242
243createFromBuilder(builder: CustomBuilder): Promise<image.PixelMap>
244
245Renders 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.
246
247> **NOTE**
248>
249> 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.
250>
251> If a component is on a time-consuming task, for example, an [\<Image>](../arkui-ts/ts-basic-components-image.md) or [\<Web>](../arkui-ts/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.
252
253**System capability**: SystemCapability.ArkUI.ArkUI.Full
254
255**Parameters**
256
257| Name    | Type                                      | Mandatory  | Description        |
258| ------- | ---------------------------------------- | ---- | ---------- |
259| builder | [CustomBuilder](../arkui-ts/ts-types.md#custombuilder8) | Yes   | Builder of the custom component.<br>**NOTE**<br>The global builder is not supported.|
260
261**Return value**
262
263| Type                           | Description      |
264| ----------------------------- | -------- |
265| Promise&lt;image.[PixelMap](js-apis-image.md#pixelmap7)&gt; | Promise used to return the result.|
266
267**Error codes**
268
269| ID | Error Message                                    |
270| ------ | ---------------------------------------- |
271| 100001 | if builder is not a valid build function. |
272
273**Example**
274
275```ts
276import componentSnapshot from '@ohos.arkui.componentSnapshot'
277import image from '@ohos.multimedia.image'
278import componentUtils from '@ohos.arkui.componentUtils'
279
280@Entry
281@Component
282struct OffscreenSnapshotExample {
283  @State pixmap: image.PixelMap | undefined = undefined
284
285  @Builder
286  RandomBuilder() {
287    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
288      Text('Test menu item 1')
289        .fontSize(20)
290        .width(100)
291        .height(50)
292        .textAlign(TextAlign.Center)
293      Divider().height(10)
294      Text('Test menu item 2')
295        .fontSize(20)
296        .width(100)
297        .height(50)
298        .textAlign(TextAlign.Center)
299    }
300    .width(100)
301    .id("builder")
302  }
303
304  build() {
305    Column() {
306      Button("click to generate offscreen UI snapshot")
307        .onClick(() => {
308          componentSnapshot.createFromBuilder(()=>{this.RandomBuilder()})
309            .then((pixmap: image.PixelMap) => {
310              this.pixmap = pixmap
311              // save pixmap to file
312              // ....
313              // get component size and location
314              let info = componentUtils.getRectangleById("builder")
315              console.log(info.size.width + ' ' + info.size.height + ' ' + info.localOffset.x + ' ' + info.localOffset.y + ' ' + info.windowOffset.x + ' ' + info.windowOffset.y)
316            }).catch((err:Error) => {
317            console.log("error: " + err)
318          })
319        })
320      Image(this.pixmap)
321        .margin(10)
322        .height(100)
323        .width(100)
324    }.width('80%').margin({ left: 10, top: 5, bottom: 5 }).height(200)
325    .border({ color: '#880606', width: 2 })
326  }
327}
328```
329