• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.arkui.componentSnapshot (组件截图)
2
3本模块提供获取组件截图的能力,包括已加载的组件的截图和没有加载的组件的截图。组件截图只能够截取组件大小的区域,如果组件的绘制超出了它的区域,或子组件的绘制超出了父组件的区域,这些在组件区域外绘制的内容不会在截图中呈现。兄弟节点堆叠在组件区域内,截图不会显示兄弟组件。
4
5缩放、平移、旋转等图形变换属性只对被截图组件的子组件生效;对目标组件本身应用图形变换属性不生效,显示的是还是图形变换前的效果。
6
7> **说明:**
8>
9> 本模块首批接口从 API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
10>
11>对于使用[XComponent](arkui-ts/ts-basic-components-xcomponent.md)的场景,例如:Video或者相机流媒体展示类组件,不建议使用组件截图相关接口,建议从[surface](../apis-image-kit/js-apis-image.md#imagecreatepixelmapfromsurface11)直接获取图片。
12>
13>如果组件自身内容不能填满组件大小区域,那么剩余位置截图返回的内容为透明像素。如果组件使用了[图像效果](arkui-ts/ts-universal-attributes-image-effect.md)类属性或其他的效果类属性,则可能产生非用户预期的截图结果。请排查是否需要填充组件透明内容区域,或使用[窗口截图](js-apis-window.md#snapshot9)替代。
14>
15> 示例效果请以真机运行为准,当前 IDE 预览器不支持。
16
17
18## 导入模块
19
20```ts
21import { componentSnapshot } from '@kit.ArkUI';
22```
23
24## componentSnapshot.get<sup>(deprecated)</sup>
25
26get(id: string, callback: AsyncCallback<image.PixelMap>, options?: SnapshotOptions): void
27
28获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。通过回调返回结果。
29
30> **说明:**
31>
32> 从API version 18开始废弃,建议使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12)获取[ComponentSnapshot](js-apis-arkui-UIContext.md#componentsnapshot12)实例,再通过此实例调用替代方法[get](js-apis-arkui-UIContext.md#get12)。
33>
34> 从API version 12开始,可以通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12)方法获取当前UI上下文关联的[ComponentSnapshot](js-apis-arkui-UIContext.md#componentsnapshot12)对象。
35>
36> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。
37
38**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
39
40**系统能力:** SystemCapability.ArkUI.ArkUI.Full
41
42**参数:**
43
44| 参数名      | 类型                                  | 必填   | 说明                                       |
45| -------- | ----------------------------------- | ---- | ---------------------------------------- |
46| id       | string                              | 是    | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识)。 |
47| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | 是    | 截图返回结果的回调。                               |
48| options<sup>12+</sup>       | [SnapshotOptions](#snapshotoptions12)                              | 否    | 截图相关的自定义参数。 |
49
50**错误码:**
51
52以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
53
54| 错误码ID | 错误信息            |
55| -------- | ------------------- |
56| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
57| 100001   | Invalid ID. |
58
59**示例:**
60
61> **说明:**
62>
63> 直接使用componentSnapshot可能导致实例不明确的问题,建议使用[getUIContext](js-apis-arkui-UIContext.md#uicontext)获取UIContext实例,并使用[getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12)获取绑定实例的componentSnapshot。
64
65```ts
66import { componentSnapshot } from '@kit.ArkUI';
67import { image } from '@kit.ImageKit';
68
69@Entry
70@Component
71struct SnapshotExample {
72  @State pixmap: image.PixelMap | undefined = undefined
73
74  build() {
75    Column() {
76      Row() {
77        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
78        Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root")
79      }
80      Button("click to generate UI snapshot")
81        .onClick(() => {
82          // 建议使用this.getUIContext().getComponentSnapshot().get()
83          componentSnapshot.get("root", (error: Error, pixmap: image.PixelMap) => {
84            if (error) {
85              console.log("error: " + JSON.stringify(error))
86              return;
87            }
88            this.pixmap = pixmap
89          }, {scale : 2, waitUntilRenderFinished : true})
90        }).margin(10)
91    }
92    .width('100%')
93    .height('100%')
94    .alignItems(HorizontalAlign.Center)
95  }
96}
97```
98
99![componentget](figures/componentget.gif)
100
101## componentSnapshot.get<sup>(deprecated)</sup>
102
103get(id: string, options?: SnapshotOptions): Promise<image.PixelMap>
104
105获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。通过Promise返回结果。
106
107> **说明:**
108>
109> 从API version 18开始废弃,建议使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12)获取[ComponentSnapshot](js-apis-arkui-UIContext.md#componentsnapshot12)实例,再通过此实例调用替代方法[get](js-apis-arkui-UIContext.md#get12-1)。
110>
111> 从API version 12开始,可以通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12)方法获取当前UI上下文关联的[ComponentSnapshot](js-apis-arkui-UIContext.md#componentsnapshot12)对象。
112>
113> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。
114
115**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
116
117**系统能力:** SystemCapability.ArkUI.ArkUI.Full
118
119**参数:**
120
121| 参数名  | 类型     | 必填   | 说明                                       |
122| ---- | ------ | ---- | ---------------------------------------- |
123| id   | string | 是    | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识)。 |
124| options<sup>12+</sup>       | [SnapshotOptions](#snapshotoptions12)                              | 否    | 截图相关的自定义参数。 |
125
126**返回值:**
127
128| 类型                            | 说明       |
129| ----------------------------- | -------- |
130| Promise&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | 截图返回的结果。 |
131
132**错误码:**
133
134以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
135
136| 错误码ID  | 错误信息                |
137| ------ | ------------------- |
138| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
139| 100001 | Invalid ID. |
140
141**示例:**
142
143> **说明:**
144>
145> 直接使用componentSnapshot可能导致实例不明确的问题,建议使用[getUIContext](js-apis-arkui-UIContext.md#uicontext)获取UIContext实例,并使用[getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12)获取绑定实例的componentSnapshot。
146
147```ts
148import { componentSnapshot } from '@kit.ArkUI';
149import { image } from '@kit.ImageKit';
150
151@Entry
152@Component
153struct SnapshotExample {
154  @State pixmap: image.PixelMap | undefined = undefined
155
156  build() {
157    Column() {
158      Row() {
159        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
160        Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root")
161      }
162      Button("click to generate UI snapshot")
163        .onClick(() => {
164          // 建议使用this.getUIContext().getComponentSnapshot().get()
165          componentSnapshot.get("root", {scale : 2, waitUntilRenderFinished : true})
166            .then((pixmap: image.PixelMap) => {
167              this.pixmap = pixmap
168            }).catch((err:Error) => {
169            console.log("error: " + err)
170          })
171        }).margin(10)
172    }
173    .width('100%')
174    .height('100%')
175    .alignItems(HorizontalAlign.Center)
176  }
177}
178```
179
180![componentget](figures/componentget.gif)
181
182## componentSnapshot.createFromBuilder<sup>(deprecated)</sup>
183
184createFromBuilder(builder: CustomBuilder, callback: AsyncCallback<image.PixelMap>, delay?: number, checkImageStatus?: boolean, options?: SnapshotOptions): void
185
186在应用后台渲染CustomBuilder自定义组件,并输出其截图。通过回调返回结果并支持在回调中获取离屏组件绘制区域坐标和大小。
187
188> **说明:**
189>
190> 从API version 18开始废弃,建议使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12)获取[ComponentSnapshot](js-apis-arkui-UIContext.md#componentsnapshot12)实例,再通过此实例调用替代方法[createFromBuilder](js-apis-arkui-UIContext.md#createfrombuilder12)。
191>
192> 从API version 12开始,可以通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12)方法获取当前UI上下文关联的[ComponentSnapshot](js-apis-arkui-UIContext.md#componentsnapshot12)对象。
193>
194> 由于需要等待组件构建、渲染成功,离屏截图的回调有500ms以内的延迟。
195>
196> builder中的组件不支持设置动画相关的属性,如[transition](arkui-ts/ts-transition-animation-component.md)。
197>
198> 部分执行耗时任务的组件可能无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的[Image](arkui-ts/ts-basic-components-image.md)组件、[Web](../apis-arkweb/ts-basic-components-web.md)组件。
199
200**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
201
202**系统能力:** SystemCapability.ArkUI.ArkUI.Full
203
204**参数:**
205
206| 参数名      | 类型                                       | 必填   | 说明         |
207| -------- | ---------------------------------------- | ---- | ---------- |
208| builder  | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | 是    | 自定义组件构建函数。<br/>**说明:** 不支持全局builder。|
209| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt;      | 是    | 截图返回结果的回调。支持在回调中获取离屏组件绘制区域坐标和大小。 |
210| delay<sup>12+</sup>   | number | 否    | 指定触发截图指令的延迟时间。当布局中使用了图片组件时,需要指定延迟时间,以便系统解码图片资源。资源越大,解码需要的时间越长,建议尽量使用不需要解码的PixelMap资源。<br/> 当使用PixelMap资源或对Image组件设置syncload为true时,可以配置delay为0,强制不等待触发截图。该延迟时间并非指接口从调用到返回的时间,由于系统需要对传入的builder进行临时离屏构建,因此返回的时间通常要比该延迟时间长。<br/>**说明:** 截图接口传入的builder中,不应使用状态变量控制子组件的构建,如果必须要使用,在调用截图接口时,也不应再有变化,以避免出现截图不符合预期的情况。<br/> 默认值:300 <br/> 单位:毫秒 <br/> 取值范围:[0, +∞),小于0时按默认值处理。 |
211| checkImageStatus<sup>12+</sup>  | boolean | 否    | 指定是否允许在截图之前,校验图片解码状态。如果为true,则会在截图之前检查所有Image组件是否已经解码完成,如果没有完成检查,则会放弃截图并返回异常。<br/>默认值:false|
212| options<sup>12+</sup>       | [SnapshotOptions](#snapshotoptions12)           | 否    | 截图相关的自定义参数。 |
213
214**错误码:**
215
216以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
217
218| 错误码ID | 错误信息                                                     |
219| -------- | ------------------------------------------------------------ |
220| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
221| 100001   | The builder is not a valid build function.                   |
222| 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. |
223
224**示例:**
225
226> **说明:**
227>
228> 直接使用componentSnapshot可能导致实例不明确的问题,建议使用[getUIContext](js-apis-arkui-UIContext.md#uicontext)获取UIContext实例,并使用[getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12)获取绑定实例的componentSnapshot。
229
230```ts
231import { componentSnapshot } from '@kit.ArkUI';
232import { image } from '@kit.ImageKit';
233
234@Entry
235@Component
236struct OffscreenSnapshotExample {
237  @State pixmap: image.PixelMap | undefined = undefined
238
239  @Builder
240  RandomBuilder() {
241    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
242      Text('Test menu item 1')
243        .fontSize(20)
244        .width(100)
245        .height(50)
246        .textAlign(TextAlign.Center)
247      Divider().height(10)
248      Text('Test menu item 2')
249        .fontSize(20)
250        .width(100)
251        .height(50)
252        .textAlign(TextAlign.Center)
253    }
254    .width(100)
255    .id("builder")
256  }
257
258  build() {
259    Column() {
260      Button("click to generate offscreen UI snapshot")
261        .onClick(() => {
262          // 建议使用this.getUIContext().getComponentSnapshot().createFromBuilder()
263          componentSnapshot.createFromBuilder(()=>{this.RandomBuilder()},
264            (error: Error, pixmap: image.PixelMap) => {
265              if(error){
266                console.log("error: " + JSON.stringify(error))
267                return;
268              }
269              this.pixmap = pixmap
270              // save pixmap to file
271              // ....
272              // get component size and location
273              let info = this.getUIContext().getComponentUtils().getRectangleById("builder")
274              console.log(info.size.width + ' ' + info.size.height + ' ' + info.localOffset.x + ' ' + info.localOffset.y + ' ' + info.windowOffset.x + ' ' + info.windowOffset.y)
275            }, 320, true, {scale : 2, waitUntilRenderFinished : true})
276        })
277      Image(this.pixmap)
278        .margin(10)
279        .height(200)
280        .width(200)
281        .border({ color: Color.Black, width: 2 })
282    }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
283  }
284}
285```
286
287![componentcreate](figures/componentcreate.gif)
288
289## componentSnapshot.createFromBuilder<sup>(deprecated)</sup>
290
291createFromBuilder(builder: CustomBuilder, delay?: number, checkImageStatus?: boolean, options?: SnapshotOptions): Promise<image.PixelMap>
292
293在应用后台渲染CustomBuilder自定义组件,并输出其截图。通过Promise返回结果并支持获取离屏组件绘制区域坐标和大小。
294
295> **说明:**
296>
297> 从API version 18开始废弃,建议使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12)获取[ComponentSnapshot](js-apis-arkui-UIContext.md#componentsnapshot12)实例,再通过此实例调用替代方法[createFromBuilder](js-apis-arkui-UIContext.md#createfrombuilder12-1)。
298>
299> 从API version 12开始,可以通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12)方法获取当前UI上下文关联的[ComponentSnapshot](js-apis-arkui-UIContext.md#componentsnapshot12)对象。
300>
301> 由于需要等待组件构建、渲染成功,离屏截图的回调有500ms以内的延迟。
302>
303> builder中的组件不支持设置动画相关的属性,如[transition](arkui-ts/ts-transition-animation-component.md)。
304>
305> 部分执行耗时任务的组件可能无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的[Image](arkui-ts/ts-basic-components-image.md)组件、[Web](../apis-arkweb/ts-basic-components-web.md)组件。
306
307**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
308
309**系统能力:** SystemCapability.ArkUI.ArkUI.Full
310
311**参数:**
312
313| 参数名     | 类型                                       | 必填   | 说明         |
314| ------- | ---------------------------------------- | ---- | ---------- |
315| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | 是    | 自定义组件构建函数。<br/>**说明:** 不支持全局builder。 |
316| delay<sup>12+</sup>   | number | 否    | 指定触发截图指令的延迟时间。当布局中使用了图片组件时,需要指定延迟时间,以便系统解码图片资源。资源越大,解码需要的时间越长,建议尽量使用不需要解码的PixelMap资源。<br/> 当使用PixelMap资源或对Image组件设置syncload为true时,可以配置delay为0,强制不等待触发截图。该延迟时间并非指接口从调用到返回的时间,由于系统需要对传入的builder进行临时离屏构建,因此返回的时间通常要比该延迟时间长。<br/>**说明:** 截图接口传入的builder中,不应使用状态变量控制子组件的构建,如果必须要使用,在调用截图接口时,也不应再有变化,以避免出现截图不符合预期的情况。<br/> 默认值:300 <br/> 单位:毫秒|
317| checkImageStatus<sup>12+</sup>  | boolean | 否    | 指定是否允许在截图之前,校验图片解码状态。如果为true,则会在截图之前检查所有Image组件是否已经解码完成,如果没有完成检查,则会放弃截图并返回异常。<br/>默认值:false|
318| options<sup>12+</sup>       | [SnapshotOptions](#snapshotoptions12)           | 否    | 截图相关的自定义参数。 |
319
320**返回值:**
321
322| 类型                            | 说明       |
323| ----------------------------- | -------- |
324| Promise&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | 截图返回的结果。 |
325
326**错误码:**
327以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
328
329| 错误码ID  | 错误信息                                     |
330| ------ | ---------------------------------------- |
331| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
332| 100001 | The builder is not a valid build function. |
333| 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. |
334
335**示例:**
336
337> **说明:**
338>
339> 直接使用componentSnapshot可能导致实例不明确的问题,建议使用[getUIContext](js-apis-arkui-UIContext.md#uicontext)获取UIContext实例,并使用[getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12)获取绑定实例的componentSnapshot。
340
341```ts
342import { componentSnapshot } from '@kit.ArkUI'
343import { image } from '@kit.ImageKit'
344
345@Entry
346@Component
347struct OffscreenSnapshotExample {
348  @State pixmap: image.PixelMap | undefined = undefined
349
350  @Builder
351  RandomBuilder() {
352    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
353      Text('Test menu item 1')
354        .fontSize(20)
355        .width(100)
356        .height(50)
357        .textAlign(TextAlign.Center)
358      Divider().height(10)
359      Text('Test menu item 2')
360        .fontSize(20)
361        .width(100)
362        .height(50)
363        .textAlign(TextAlign.Center)
364    }
365    .width(100)
366    .id("builder")
367  }
368
369  build() {
370    Column() {
371      Button("click to generate offscreen UI snapshot")
372        .onClick(() => {
373          // 建议使用this.getUIContext().getComponentSnapshot().createFromBuilder()
374          componentSnapshot.createFromBuilder(()=>{this.RandomBuilder()}, 320, true, {scale : 2, waitUntilRenderFinished : true})
375            .then((pixmap: image.PixelMap) => {
376              this.pixmap = pixmap
377              // save pixmap to file
378              // ....
379              // get component size and location
380              let info = this.getUIContext().getComponentUtils().getRectangleById("builder")
381              console.log(info.size.width + ' ' + info.size.height + ' ' + info.localOffset.x + ' ' + info.localOffset.y + ' ' + info.windowOffset.x + ' ' + info.windowOffset.y)
382            }).catch((err:Error) => {
383            console.log("error: " + err)
384          })
385        })
386      Image(this.pixmap)
387        .margin(10)
388        .height(200)
389        .width(200)
390        .border({ color: Color.Black, width: 2 })
391    }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
392  }
393}
394```
395
396![componentcreate](figures/componentcreate.gif)
397
398## componentSnapshot.getSync<sup>12+</sup>
399
400getSync(id: string, options?: SnapshotOptions): image.PixelMap
401
402获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。同步等待截图完成返回[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)。
403
404> **说明:**
405>
406> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。
407
408**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
409
410**系统能力:** SystemCapability.ArkUI.ArkUI.Full
411
412**参数:**
413
414| 参数名  | 类型     | 必填   | 说明                                       |
415| ---- | ------ | ---- | ---------------------------------------- |
416| id   | string | 是    | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识)。 |
417| options       | [SnapshotOptions](#snapshotoptions12)                              | 否    | 截图相关的自定义参数。 |
418
419**返回值:**
420
421| 类型                            | 说明       |
422| ----------------------------- | -------- |
423| image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | 截图返回的结果。 |
424
425**错误码:**
426
427以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
428
429| 错误码ID  | 错误信息                |
430| ------ | ------------------- |
431| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
432| 100001 | Invalid ID. |
433| 160002 | Timeout. |
434
435**示例:**
436
437> **说明:**
438>
439> 直接使用componentSnapshot可能导致实例不明确的问题,建议使用[getUIContext](js-apis-arkui-UIContext.md#uicontext)获取UIContext实例,并使用[getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12)获取绑定实例的componentSnapshot。
440
441```ts
442import { componentSnapshot } from '@kit.ArkUI';
443import { image } from '@kit.ImageKit';
444
445@Entry
446@Component
447struct SnapshotExample {
448  @State pixmap: image.PixelMap | undefined = undefined
449
450  build() {
451    Column() {
452      Row() {
453        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
454        Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root")
455      }
456      Button("click to generate UI snapshot")
457        .onClick(() => {
458          try {
459          // 建议使用this.getUIContext().getComponentSnapshot().getSync()
460            let pixelmap = componentSnapshot.getSync("root", {scale : 2, waitUntilRenderFinished : true})
461            this.pixmap = pixelmap
462          } catch (error) {
463            console.error("getSync errorCode: " + error.code + " message: " + error.message)
464          }
465        }).margin(10)
466    }
467    .width('100%')
468    .height('100%')
469    .alignItems(HorizontalAlign.Center)
470  }
471}
472```
473
474![componentget](figures/componentget.gif)
475
476## SnapshotOptions<sup>12+</sup>
477
478**系统能力:** SystemCapability.ArkUI.ArkUI.Full
479
480| 名称           | 类型             | 必填           | 说明                         |
481| ---------------|------------     | -----------------------------| -----------------------------|
482| scale           | number | 否 | 指定截图时图形侧绘制pixelmap的缩放比例,比例过大时截图时间会变长,或者截图可能会失败。<br/>取值范围:[0, +∞),当小于等于0时按默认情况处理。 <br/> 默认值:1 <br/>**说明:** <br/>请不要截取过大尺寸的图片,截图不建议超过屏幕尺寸的大小。当要截取的图片目标长宽超过底层限制时,截图会返回失败,不同设备的底层限制不同。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。    |
483| waitUntilRenderFinished    | boolean | 否 | 设置是否强制系统在截图前等待所有绘制指令执行完毕。true表示强制系统在截图前等待所有绘制指令执行完毕,false表示不强制系统在截图前等待所有绘制指令执行完毕。该选项可尽可能确保截图内容是最新的状态,应尽量开启。需要注意的是,开启后接口可能需要更长的时间返回,具体的时间依赖页面当时时刻需要重绘区域的大小。<br>默认值:false <br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。         |
484| region<sup>15+</sup> | [SnapshotRegionType](#snapshotregiontype15) | 否 | 指定截图的矩形区域范围,默认为整个组件。<br/>**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 |
485
486## SnapshotRegionType<sup>15+</sup>
487
488type SnapshotRegionType =  SnapshotRegion | LocalizedSnapshotRegion
489
490表示组件截图区域,取值类型为下表中的任一类型。
491
492**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。
493
494**系统能力:** SystemCapability.ArkUI.ArkUI.Full
495
496| 类型   | 说明   |
497| ------ | ------ |
498| [SnapshotRegion](#snapshotregion15) | 表示组件截图的矩形区域。 |
499| [LocalizedSnapshotRegion ](#localizedsnapshotregion15) | 表示组件截图的矩形区域,根据布局方向确定是否对矩形区域水平翻转,若布局方向为RTL,则把指定的截图区域做左右翻转处理以适应RTL布局方向。 |
500
501## SnapshotRegion<sup>15+</sup>
502
503定义组件截图的矩形区域。
504
505**系统能力:** SystemCapability.ArkUI.ArkUI.Full
506
507**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。
508
509| 名称   | 类型   | 必填 | 说明                                    |
510| ------ | ------ | ---- | --------------------------------------- |
511| left   | number | 是   | 截图区域矩形左上角的x轴坐标,单位为px。 |
512| top    | number | 是   | 截图区域矩形左上角的y轴坐标,单位为px。 |
513| right  | number | 是   | 截图区域矩形右下角的x轴坐标,单位为px。 |
514| bottom | number | 是   | 截图区域矩形右下角的y轴坐标,单位为px。 |
515
516## LocalizedSnapshotRegion<sup>15+</sup>
517
518定义组件截图的矩形区域,start和end的值在布局方向为LTR时指定为left和right,在布局方向为RTL时指定为right和left。
519
520**系统能力:** SystemCapability.ArkUI.ArkUI.Full
521
522**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。
523
524| 名称   | 类型   | 必填 | 说明                                                         |
525| ------ | ------ | ---- | ------------------------------------------------------------ |
526| start  | number | 是   | 布局方向为LTR时表示截图区域矩形左上角的x轴坐标,布局方向为RTL时表示截图区域矩形右下角的x轴坐标,单位为px。 |
527| top    | number | 是   | 布局方向为LTR时表示截图区域矩形左上角的y轴坐标,布局方向为RTL时表示截图区域矩形右下角的y轴坐标,单位为px。 |
528| end    | number | 是   | 布局方向为LTR时表示截图区域矩形右上角的x轴坐标,布局方向为RTL时表示截图区域矩形左下角的x轴坐标,单位为px。 |
529| bottom | number | 是   | 布局方向为LTR时表示截图区域矩形右上角的y轴坐标,布局方向为RTL时表示截图区域矩形左下角的y轴坐标,单位为px。 |