• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Class (ComponentSnapshot)
2<!--Kit: ArkUI-->
3<!--Subsystem: ArkUI-->
4<!--Owner: @jiangtao92-->
5<!--Designer: @piggyguy-->
6<!--Tester: @songyanhong-->
7<!--Adviser: @HelloCrease-->
8提供获取组件截图的能力,包括已加载的组件的截图和没有加载的组件的截图。
9
10> **说明:**
11>
12> - 本模块首批接口从API version 10开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
13>
14> - 本Class首批接口从API version 12开始支持。
15>
16> - 以下API需先使用UIContext中的[getComponentSnapshot()](./arkts-apis-uicontext-uicontext.md#getcomponentsnapshot12)方法获取ComponentSnapshot对象,再通过此实例调用对应方法。
17>
18> - 缩放、平移、旋转等图形变换属性只对被截图组件的子组件生效;对目标组件本身应用图形变换属性不生效,显示的是还是图形变换前的效果。
19
20## get<sup>12+</sup>
21
22get(id: string, callback: AsyncCallback<image.PixelMap>, options?: componentSnapshot.SnapshotOptions): void
23
24获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md),找到对应组件进行截图。通过回调返回结果。
25
26> **说明:**
27>
28> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。
29
30**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
31
32**系统能力:** SystemCapability.ArkUI.ArkUI.Full
33
34**参数:**
35
36| 参数名   | 类型                                                         | 必填 | 说明                                                         |
37| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
38| id       | string                                                       | 是   | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。<br/>**说明:** 不支持未挂树组件,当传入的组件标识是离屏或缓存未挂树的节点时,系统不会对其进行截图。 |
39| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)&lt;image.[PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md)&gt; | 是   | 截图返回结果的回调。                                         |
40| options       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | 否    | 截图相关的自定义参数。 |
41
42**错误码:**
43
44以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[截图错误码](errorcode-snapshot.md)。
45
46| 错误码ID | 错误信息                                                     |
47| -------- | ------------------------------------------------------------ |
48| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
49| 100001   | Invalid ID.                                                  |
50
51**示例:**
52
53```ts
54import { image } from '@kit.ImageKit';
55import { UIContext } from '@kit.ArkUI';
56
57@Entry
58@Component
59struct SnapshotExample {
60  @State pixmap: image.PixelMap | undefined = undefined;
61  uiContext: UIContext = this.getUIContext();
62  build() {
63    Column() {
64      Row() {
65        Image(this.pixmap).width(150).height(150).border({ color: Color.Black, width: 2 }).margin(5)
66        Image($r('app.media.img')).autoResize(true).width(150).height(150).margin(5).id("root")
67      }
68      Button("click to generate UI snapshot")
69        .onClick(() => {
70          this.uiContext.getComponentSnapshot().get("root", (error: Error, pixmap: image.PixelMap) => {
71            if (error) {
72              console.error("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## get<sup>12+</sup>
87
88get(id: string, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>
89
90获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md),找到对应组件进行截图。通过Promise返回结果。
91
92> **说明:**
93>
94> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。
95
96**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
97
98**系统能力:** SystemCapability.ArkUI.ArkUI.Full
99
100**参数:**
101
102| 参数名 | 类型   | 必填 | 说明                                                         |
103| ------ | ------ | ---- | ------------------------------------------------------------ |
104| id     | string | 是   | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。<br/>**说明:** 不支持未挂树组件,当传入的组件标识是离屏或缓存未挂树的节点时,系统不会对其进行截图。 |
105| options       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | 否    | 截图相关的自定义参数。 |
106
107**返回值:**
108
109| 类型                                                         | 说明             |
110| ------------------------------------------------------------ | ---------------- |
111| Promise&lt;image.[PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md)&gt; | 截图返回的结果。 |
112
113**错误码:**
114
115以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[截图错误码](errorcode-snapshot.md)。
116
117| 错误码ID | 错误信息                                                     |
118| -------- | ------------------------------------------------------------ |
119| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
120| 100001   | Invalid ID.                                                  |
121
122**示例:**
123
124```ts
125import { image } from '@kit.ImageKit';
126import { UIContext } from '@kit.ArkUI';
127
128@Entry
129@Component
130struct SnapshotExample {
131  @State pixmap: image.PixelMap | undefined = undefined;
132  uiContext: UIContext = this.getUIContext();
133
134  build() {
135    Column() {
136      Row() {
137        Image(this.pixmap).width(150).height(150).border({ color: Color.Black, width: 2 }).margin(5)
138        Image($r('app.media.icon')).autoResize(true).width(150).height(150).margin(5).id("root")
139      }
140      Button("click to generate UI snapshot")
141        .onClick(() => {
142          this.uiContext.getComponentSnapshot()
143            .get("root", { scale: 2, waitUntilRenderFinished: true })
144            .then((pixmap: image.PixelMap) => {
145              this.pixmap = pixmap;
146            })
147            .catch((err: Error) => {
148              console.error("error: " + err);
149            })
150        }).margin(10)
151    }
152    .width('100%')
153    .height('100%')
154    .alignItems(HorizontalAlign.Center)
155  }
156}
157```
158
159## createFromBuilder<sup>12+</sup>
160
161createFromBuilder(builder: CustomBuilder, callback: AsyncCallback<image.PixelMap>, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): void
162
163传入[CustomBuilder](arkui-ts/ts-types.md#custombuilder8)自定义组件,系统对其进行离屏构建后进行截图,并通过回调返回结果。
164> **说明:**
165>
166> 由于需要等待组件构建、渲染成功,离屏截图的回调有500ms以内的延迟,不适宜使用在对性能敏感的场景。
167>
168> 部分执行耗时任务的组件可能无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的[Image](arkui-ts/ts-basic-components-image.md)组件、[Web](../apis-arkweb/arkts-basic-components-web.md)组件。
169
170**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
171
172**系统能力:** SystemCapability.ArkUI.ArkUI.Full
173
174**参数:**
175
176| 参数名   | 类型                                                         | 必填 | 说明                                                         |
177| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
178| builder  | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8)         | 是   | 自定义组件构建函数。<br/>**说明:** 不支持全局builder。<br/>builder的根组件宽高为0时,截图操作会失败并抛出100001错误码。      |
179| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)&lt;image.[PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md)&gt; | 是   | 截图返回结果的回调。支持在回调中获取离屏组件绘制区域坐标和大小。 |
180| delay   | number | 否    | 指定触发截图指令的延迟时间。当布局中使用了图片组件时,需要指定延迟时间,以便系统解码图片资源。资源越大,解码需要的时间越长,建议尽量使用不需要解码的PixelMap资源。<br/> 当使用PixelMap资源或对Image组件设置syncload为true时,可以配置delay为0,强制不等待触发截图。该延迟时间并非指接口从调用到返回的时间,由于系统需要对传入的builder进行临时离屏构建,因此返回的时间通常要比该延迟时间长。<br/>**说明:** 截图接口传入的builder中,不应使用状态变量控制子组件的构建,如果必须要使用,在调用截图接口时,也不应再有变化,以避免出现截图不符合预期的情况。<br/> 默认值:300 <br/> 单位:毫秒 <br/> 取值范围:[0, +∞),小于0时按默认值处理。 |
181| checkImageStatus  | boolean | 否    | 指定是否允许在截图之前,校验图片解码状态。如果为true,则会在截图之前检查所有Image组件是否已经解码完成,如果没有完成检查,则会放弃截图并返回异常。<br/>默认值:false|
182| options       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否    | 截图相关的自定义参数。 |
183
184**错误码:**
185
186以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[截图错误码](errorcode-snapshot.md)。
187
188| 错误码ID | 错误信息                                                     |
189| -------- | ------------------------------------------------------------ |
190| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
191| 100001   | The builder is not a valid build function.                   |
192| 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. |
193
194**示例:**
195
196```ts
197import { image } from '@kit.ImageKit';
198import { UIContext } from '@kit.ArkUI';
199
200@Entry
201@Component
202struct ComponentSnapshotExample {
203  @State pixmap: image.PixelMap | undefined = undefined;
204  uiContext: UIContext = this.getUIContext();
205  @Builder
206  RandomBuilder() {
207    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
208      Text('Test menu item 1')
209        .fontSize(20)
210        .width(100)
211        .height(50)
212        .textAlign(TextAlign.Center)
213      Divider().height(10)
214      Text('Test menu item 2')
215        .fontSize(20)
216        .width(100)
217        .height(50)
218        .textAlign(TextAlign.Center)
219    }
220    .width(100)
221    .id("builder")
222  }
223
224  build() {
225    Column() {
226      Button("click to generate UI snapshot")
227        .onClick(() => {
228          this.uiContext.getComponentSnapshot().createFromBuilder(() => {
229            this.RandomBuilder()
230          },
231            (error: Error, pixmap: image.PixelMap) => {
232              if (error) {
233                console.error("error: " + JSON.stringify(error));
234                return;
235              }
236              this.pixmap = pixmap;
237            }, 320, true, { scale: 2, waitUntilRenderFinished: true });
238        })
239      Image(this.pixmap)
240        .margin(10)
241        .height(200)
242        .width(200)
243        .border({ color: Color.Black, width: 2 })
244    }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
245  }
246}
247```
248
249## createFromBuilder<sup>12+</sup>
250
251createFromBuilder(builder: CustomBuilder, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>
252
253传入[CustomBuilder](arkui-ts/ts-types.md#custombuilder8)自定义组件,系统对其进行离屏构建后进行截图,并通过回调返回结果。
254
255> **说明:**
256>
257> 由于需要等待组件构建、渲染成功,离屏截图的回调有500ms以内的延迟,不适宜使用在对性能敏感的场景。
258>
259> 部分执行耗时任务的组件可能无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的[Image](arkui-ts/ts-basic-components-image.md)组件、[Web](../apis-arkweb/arkts-basic-components-web.md)组件。
260
261**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
262
263**系统能力:** SystemCapability.ArkUI.ArkUI.Full
264
265**参数:**
266
267| 参数名  | 类型                                                 | 必填 | 说明                                                    |
268| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- |
269| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | 是   | 自定义组件构建函数。<br/>**说明:** 不支持全局builder。<br/>builder的根组件宽高为0时,截图操作会失败并抛出100001错误码。 |
270| delay   | number | 否    | 指定触发截图指令的延迟时间。当布局中使用了图片组件时,需要指定延迟时间,以便系统解码图片资源。资源越大,解码需要的时间越长,建议尽量使用不需要解码的PixelMap资源。<br/> 当使用PixelMap资源或对Image组件设置syncload为true时,可以配置delay为0,强制不等待触发截图。该延迟时间并非指接口从调用到返回的时间,由于系统需要对传入的builder进行临时离屏构建,因此返回的时间通常要比该延迟时间长。<br/>**说明:** 截图接口传入的builder中,不应使用状态变量控制子组件的构建,如果必须要使用,在调用截图接口时,也不应再有变化,以避免出现截图不符合预期的情况。<br/> 默认值:300 <br/> 单位:毫秒<br/> 取值范围:[0, +∞),小于0时按默认值处理。|
271| checkImageStatus  | boolean | 否    | 指定是否允许在截图之前,校验图片解码状态。如果为true,则会在截图之前检查所有Image组件是否已经解码完成,如果没有完成检查,则会放弃截图并返回异常。<br/>默认值:false|
272| options       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)           | 否    | 截图相关的自定义参数。 |
273
274**返回值:**
275
276| 类型                                                         | 说明             |
277| ------------------------------------------------------------ | ---------------- |
278| Promise&lt;image.[PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md)&gt; | 截图返回的结果。 |
279
280**错误码:**
281
282以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[截图错误码](errorcode-snapshot.md)。
283
284| 错误码ID | 错误信息                                                     |
285| -------- | ------------------------------------------------------------ |
286| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
287| 100001   | The builder is not a valid build function.                   |
288| 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. |
289
290**示例:**
291
292```ts
293import { image } from '@kit.ImageKit';
294import { UIContext } from '@kit.ArkUI';
295
296@Entry
297@Component
298struct ComponentSnapshotExample {
299  @State pixmap: image.PixelMap | undefined = undefined;
300  uiContext: UIContext = this.getUIContext();
301  @Builder
302  RandomBuilder() {
303    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
304      Text('Test menu item 1')
305        .fontSize(20)
306        .width(100)
307        .height(50)
308        .textAlign(TextAlign.Center)
309      Divider().height(10)
310      Text('Test menu item 2')
311        .fontSize(20)
312        .width(100)
313        .height(50)
314        .textAlign(TextAlign.Center)
315    }
316    .width(100)
317    .id("builder")
318  }
319  build() {
320    Column() {
321      Button("click to generate UI snapshot")
322        .onClick(() => {
323          this.uiContext.getComponentSnapshot()
324            .createFromBuilder(() => {
325              this.RandomBuilder()
326            }, 320, true, { scale: 2, waitUntilRenderFinished: true })
327            .then((pixmap: image.PixelMap) => {
328              this.pixmap = pixmap;
329            })
330            .catch((err: Error) => {
331              console.error("error: " + err);
332            })
333        })
334      Image(this.pixmap)
335        .margin(10)
336        .height(200)
337        .width(200)
338        .border({ color: Color.Black, width: 2 })
339    }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
340  }
341}
342```
343
344## getSync<sup>12+</sup>
345
346getSync(id: string, options?: componentSnapshot.SnapshotOptions): image.PixelMap
347
348获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md),找到对应组件进行截图。同步等待截图完成返回[PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md)。
349
350> **说明:**
351>
352> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。
353
354**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
355
356**系统能力:** SystemCapability.ArkUI.ArkUI.Full
357
358**参数:**
359
360| 参数名  | 类型     | 必填   | 说明                                       |
361| ---- | ------ | ---- | ---------------------------------------- |
362| id   | string | 是    | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。 <br/>**说明:** 不支持未挂树组件,当传入的组件标识是离屏或缓存未挂树的节点时,系统不会对其进行截图。|
363| options       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | 否    | 截图相关的自定义参数。 |
364
365**返回值:**
366
367| 类型                            | 说明       |
368| ----------------------------- | -------- |
369| image.[PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md) | 截图返回的结果。 |
370
371**错误码:**
372
373以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[截图错误码](errorcode-snapshot.md)。
374
375| 错误码ID  | 错误信息                |
376| ------ | ------------------- |
377| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
378| 100001 | Invalid ID. |
379| 160002 | Timeout. |
380
381**示例:**
382
383```ts
384import { image } from '@kit.ImageKit';
385import { UIContext } from '@kit.ArkUI';
386
387@Entry
388@Component
389struct SnapshotExample {
390  @State pixmap: image.PixelMap | undefined = undefined;
391
392  build() {
393    Column() {
394      Row() {
395        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
396        Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root")
397      }
398      Button("click to generate UI snapshot")
399        .onClick(() => {
400          try {
401            let pixelmap = this.getUIContext().getComponentSnapshot().getSync("root", { scale: 2, waitUntilRenderFinished: true });
402            this.pixmap = pixelmap;
403          } catch (error) {
404            console.error("getSync errorCode: " + error.code + " message: " + error.message);
405          }
406        }).margin(10)
407    }
408    .width('100%')
409    .height('100%')
410    .alignItems(HorizontalAlign.Center)
411  }
412}
413```
414
415## getWithUniqueId<sup>15+</sup>
416
417getWithUniqueId(uniqueId: number, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>
418
419获取已加载的组件的截图,传入组件的[uniqueId](js-apis-arkui-frameNode.md#getuniqueid12),找到对应组件进行截图。通过Promise返回结果。
420
421> **说明:**
422>
423> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。
424
425**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。
426
427**系统能力:** SystemCapability.ArkUI.ArkUI.Full
428
429**参数:**
430
431| 参数名  | 类型     | 必填   | 说明                                       |
432| ---- | ------ | ---- | ---------------------------------------- |
433| uniqueId   | number | 是    | 目标组件的[uniqueId](js-apis-arkui-frameNode.md#getuniqueid12) <br/>**说明:** 不支持未挂树组件,当传入的组件标识是离屏或缓存未挂树的节点时,系统不会对其进行截图。|
434| options       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | 否    | 截图相关的自定义参数。 |
435
436**返回值:**
437
438| 类型                                                         | 说明             |
439| ------------------------------------------------------------ | ---------------- |
440| Promise&lt;image.[PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md)&gt; | 截图返回的结果。 |
441
442**错误码:**
443
444以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[截图错误码](errorcode-snapshot.md)。
445
446| 错误码ID | 错误信息                                                     |
447| -------- | ------------------------------------------------------------ |
448| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
449| 100001   | Invalid ID.                                                  |
450
451**示例:**
452
453```ts
454import { NodeController, FrameNode, typeNode } from '@kit.ArkUI';
455import { image } from '@kit.ImageKit';
456import { UIContext } from '@kit.ArkUI';
457
458class MyNodeController extends NodeController {
459  public node: FrameNode | null = null;
460
461  public imageNode: FrameNode | null = null;
462
463  makeNode(uiContext: UIContext): FrameNode | null {
464    this.node = new FrameNode(uiContext);
465    this.node.commonAttribute.width('100%').height('100%');
466
467    let image = typeNode.createNode(uiContext, 'Image');
468    image.initialize($r('app.media.img')).width('100%').height('100%').autoResize(true);
469    this.imageNode = image;
470
471    this.node.appendChild(image);
472    return this.node;
473  }
474}
475
476@Entry
477@Component
478struct SnapshotExample {
479  private myNodeController: MyNodeController = new MyNodeController();
480
481  @State pixmap: image.PixelMap | undefined = undefined;
482
483  build() {
484    Column() {
485      Row() {
486        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
487        NodeContainer(this.myNodeController).width(200).height(200).margin(5)
488      }
489      Button("UniqueId get snapshot")
490        .onClick(() => {
491          try {
492            this.getUIContext()
493              .getComponentSnapshot()
494              .getWithUniqueId(this.myNodeController.imageNode?.getUniqueId(), { scale: 2, waitUntilRenderFinished: true })
495              .then((pixmap: image.PixelMap) => {
496                this.pixmap = pixmap;
497              })
498              .catch((err: Error) => {
499                console.log("error: " + err);
500              })
501          } catch (error) {
502            console.error("UniqueId get snapshot Error: " + JSON.stringify(error));
503          }
504        }).margin(10)
505    }
506    .width('100%')
507    .height('100%')
508    .alignItems(HorizontalAlign.Center)
509  }
510}
511```
512
513## getSyncWithUniqueId<sup>15+</sup>
514
515getSyncWithUniqueId(uniqueId: number, options?: componentSnapshot.SnapshotOptions): image.PixelMap
516
517获取已加载的组件的截图,传入组件的[uniqueId](js-apis-arkui-frameNode.md#getuniqueid12),找到对应组件进行截图。同步等待截图完成返回[PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md)。
518
519> **说明:**
520>
521> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。
522
523**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。
524
525**系统能力:** SystemCapability.ArkUI.ArkUI.Full
526
527**参数:**
528
529| 参数名  | 类型     | 必填   | 说明                                       |
530| ---- | ------ | ---- | ---------------------------------------- |
531| uniqueId   | number | 是    | 目标组件的[uniqueId](js-apis-arkui-frameNode.md#getuniqueid12)。<br/>**说明:** 不支持未挂树组件,当传入的组件标识是离屏或缓存未挂树的节点时,系统不会对其进行截图。|
532| options       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | 否    | 截图相关的自定义参数。 |
533
534**返回值:**
535
536| 类型                            | 说明       |
537| ----------------------------- | -------- |
538| image.[PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md) | 截图返回的结果。 |
539
540**错误码:**
541
542以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[截图错误码](errorcode-snapshot.md)。
543
544| 错误码ID  | 错误信息                |
545| ------ | ------------------- |
546| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
547| 100001 | Invalid ID. |
548| 160002 | Timeout. |
549
550**示例:**
551
552```ts
553import { NodeController, FrameNode, typeNode } from '@kit.ArkUI';
554import { image } from '@kit.ImageKit';
555import { UIContext } from '@kit.ArkUI';
556
557class MyNodeController extends NodeController {
558  public node: FrameNode | null = null;
559
560  public imageNode: FrameNode | null = null;
561
562  makeNode(uiContext: UIContext): FrameNode | null {
563    this.node = new FrameNode(uiContext);
564    this.node.commonAttribute.width('100%').height('100%');
565
566    let image = typeNode.createNode(uiContext, 'Image');
567    image.initialize($r('app.media.img')).width('100%').height('100%').autoResize(true);
568    this.imageNode = image;
569
570    this.node.appendChild(image);
571    return this.node;
572  }
573}
574
575@Entry
576@Component
577struct SnapshotExample {
578  private myNodeController: MyNodeController = new MyNodeController();
579
580  @State pixmap: image.PixelMap | undefined = undefined;
581
582  build() {
583    Column() {
584      Row() {
585        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
586        NodeContainer(this.myNodeController).width(200).height(200).margin(5)
587      }
588      Button("UniqueId getSync snapshot")
589        .onClick(() => {
590          try {
591            this.pixmap = this.getUIContext()
592              .getComponentSnapshot()
593              .getSyncWithUniqueId(this.myNodeController.imageNode?.getUniqueId(), { scale: 2, waitUntilRenderFinished: true });
594          } catch (error) {
595            console.error("UniqueId getSync snapshot Error: " + JSON.stringify(error));
596          }
597        }).margin(10)
598    }
599    .width('100%')
600    .height('100%')
601    .alignItems(HorizontalAlign.Center)
602  }
603}
604```
605
606## createFromComponent<sup>18+</sup>
607
608createFromComponent\<T extends Object>(content: ComponentContent\<T>, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>
609
610将传入的content对象进行截图,并通过Promise返回结果。
611
612**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
613
614**系统能力:** SystemCapability.ArkUI.ArkUI.Full
615
616**参数:**
617
618| 参数名   | 类型                                                         | 必填 | 说明                                                         |
619| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
620| content  | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md)         | 是   | 当前UIContext显示的组件内容。      |
621| delay   | number | 否    | 指定触发截图指令的延迟时间。当布局中使用了图片组件时,需要指定延迟时间,以便系统解码图片资源。资源越大,解码需要的时间越长,建议尽量使用不需要解码的PixelMap资源。<br/> 当使用PixelMap资源或对Image组件设置syncload为true时,可以配置delay为0,强制不等待触发截图。该延迟时间并非指接口从调用到返回的时间,由于系统需要对传入的builder进行临时离屏构建,因此返回的时间通常要比该延迟时间长。<br/>**说明:** 截图接口传入的builder中,不应使用状态变量控制子组件的构建,如果必须要使用,在调用截图接口时,也不应再有变化,以避免出现截图不符合预期的情况。<br/> 取值范围:[0,+∞) ,小于0时按默认值处理。<br/>默认值:300 <br/> 单位:毫秒|
622| checkImageStatus  | boolean | 否    | 指定是否允许在截图之前,校验图片解码状态。如果为true,则会在截图之前检查所有Image组件是否已经解码完成,如果没有完成检查,则会放弃截图并返回异常。<br/>默认值:false|
623| options       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否    | 截图相关的自定义参数。可以指定截图时图形侧绘制pixelmap的缩放比例与是否强制等待系统执行截图指令前所有绘制指令都执行完成之后再截图。 |
624
625**返回值:**
626
627| 类型                            | 说明       |
628| ----------------------------- | -------- |
629| Promise<image.[PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md)>  | 截图返回的结果。 |
630
631**错误码:**
632
633以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[截图错误码](errorcode-snapshot.md)。
634
635| 错误码ID | 错误信息                                                     |
636| -------- | ------------------------------------------------------------ |
637| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
638| 100001   | The builder is not a valid build function.                   |
639| 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. |
640
641**示例:**
642
643```ts
644import { image } from '@kit.ImageKit';
645import { ComponentContent } from '@kit.ArkUI';
646
647class Params {
648  text: string | undefined | null  = "";
649
650  constructor(text: string | undefined | null ) {
651    this.text = text;
652  }
653}
654
655@Builder
656function buildText(params: Params) {
657  ReusableChildComponent({ text: params.text })
658}
659
660@Component
661struct ReusableChildComponent {
662  @Prop text: string | undefined | null  = "";
663
664  aboutToReuse(params: Record<string, object>) {
665    console.log("ReusableChildComponent Reusable " + JSON.stringify(params));
666  }
667
668  aboutToRecycle(): void {
669    console.log("ReusableChildComponent aboutToRecycle " + this.text);
670  }
671
672  build() {
673    Column() {
674      Text(this.text)
675        .fontSize(90)
676        .fontWeight(FontWeight.Bold)
677        .margin({ bottom: 36 })
678        .width('100%')
679        .height('100%')
680    }.backgroundColor('#FFF0F0F0')
681  }
682}
683
684@Entry
685@Component
686struct Index {
687  @State pixmap: image.PixelMap | undefined = undefined;
688  @State message: string | undefined | null = "hello";
689  uiContext: UIContext = this.getUIContext();
690
691  build() {
692    Row() {
693      Column() {
694        Button("点击生成组件截图")
695          .onClick(() => {
696            let uiContext = this.getUIContext();
697            let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
698            this.uiContext.getComponentSnapshot()
699              .createFromComponent(contentNode
700                , 320, true, { scale: 2, waitUntilRenderFinished: true })
701              .then((pixmap: image.PixelMap) => {
702                this.pixmap = pixmap;
703              })
704              .catch((err: Error) => {
705                console.error("error: " + err);
706              })
707          })
708        Image(this.pixmap)
709          .margin(10)
710          .height(200)
711          .width(200)
712          .border({ color: Color.Black, width: 2 })
713      }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
714    }
715    .width('100%')
716    .height('100%')
717  }
718}
719```
720
721