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