• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.arkui.componentSnapshot (组件截图)
2
3本模块提供获取组件截图的能力,包括已加载的组件的截图和没有加载的组件的截图。组件截图只能够截取组件大小的区域,如果组件的绘制超出了它的区域,或子组件的绘制超出了父组件的区域,这些在组件区域外绘制的内容不会在截图中呈现。
4
5> **说明:**
6>
7> 本模块首批接口从 API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8>
9>对于使用[XComponent](arkui-ts/ts-basic-components-xcomponent.md)的场景,例如:Video或者相机流媒体展示类组件,不建议使用组件截图相关接口,建议从[surface](../apis-image-kit/js-apis-image.md#imagecreatepixelmapfromsurface11)直接获取图片。
10>
11> 示例效果请以真机运行为准,当前 IDE 预览器不支持。
12
13
14## 导入模块
15
16```ts
17import componentSnapshot from "@ohos.arkui.componentSnapshot";
18```
19
20## componentSnapshot.get
21
22get(id: string, callback: AsyncCallback<image.PixelMap>): void
23
24获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。通过回调返回结果。
25
26> **说明:**
27>
28> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。
29
30**系统能力:** SystemCapability.ArkUI.ArkUI.Full
31
32**参数:**
33
34| 参数名      | 类型                                  | 必填   | 说明                                       |
35| -------- | ----------------------------------- | ---- | ---------------------------------------- |
36| id       | string                              | 是    | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识) |
37| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | 是    | 截图返回结果的回调。                               |
38
39**错误码:**
40
41| 错误码ID | 错误信息            |
42| -------- | ------------------- |
43| 100001   | if id is not valid. |
44
45**示例:**
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      Row() {
59        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
60        Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root")
61      }
62      Button("click to generate UI snapshot")
63        .onClick(() => {
64          componentSnapshot.get("root", (error: Error, pixmap: image.PixelMap) => {
65            if (error) {
66              console.log("error: " + JSON.stringify(error))
67              return;
68            }
69            this.pixmap = pixmap
70          })
71        }).margin(10)
72    }
73    .width('100%')
74    .height('100%')
75    .alignItems(HorizontalAlign.Center)
76  }
77}
78```
79
80![componentget](figures/componentget.gif)
81
82## componentSnapshot.get
83
84get(id: string): Promise<image.PixelMap>
85
86获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。通过Promise返回结果。
87
88> **说明:**
89>
90> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。
91
92**系统能力:** SystemCapability.ArkUI.ArkUI.Full
93
94**参数:**
95
96| 参数名  | 类型     | 必填   | 说明                                       |
97| ---- | ------ | ---- | ---------------------------------------- |
98| id   | string | 是    | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识) |
99
100**返回值:**
101
102| 类型                            | 说明       |
103| ----------------------------- | -------- |
104| Promise&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | 截图返回的结果。 |
105
106**错误码:**
107
108| 错误码ID  | 错误信息                |
109| ------ | ------------------- |
110| 100001 | if id is not valid. |
111
112**示例:**
113
114```ts
115import componentSnapshot from '@ohos.arkui.componentSnapshot'
116import image from '@ohos.multimedia.image'
117
118@Entry
119@Component
120struct SnapshotExample {
121  @State pixmap: image.PixelMap | undefined = undefined
122
123  build() {
124    Column() {
125      Row() {
126        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
127        Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root")
128      }
129      Button("click to generate UI snapshot")
130        .onClick(() => {
131          componentSnapshot.get("root")
132            .then((pixmap: image.PixelMap) => {
133              this.pixmap = pixmap
134            }).catch((err:Error) => {
135            console.log("error: " + err)
136          })
137        }).margin(10)
138    }
139    .width('100%')
140    .height('100%')
141    .alignItems(HorizontalAlign.Center)
142  }
143}
144```
145
146![componentget](figures/componentget.gif)
147
148## componentSnapshot.createFromBuilder
149
150createFromBuilder(builder: CustomBuilder, callback: AsyncCallback<image.PixelMap>): void
151
152在应用后台渲染CustomBuilder自定义组件,并输出其截图。通过回调返回结果并支持在回调中获取离屏组件绘制区域坐标和大小。
153
154> **说明:**
155>
156> 由于需要等待组件构建、渲染成功,离屏截图的回调有500ms以内的延迟。
157>
158> 部分执行耗时任务的组件可能无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的[Image](arkui-ts/ts-basic-components-image.md)组件、[Web](../apis-arkweb/ts-basic-components-web.md)组件。
159
160
161**系统能力:** SystemCapability.ArkUI.ArkUI.Full
162
163**参数:**
164
165| 参数名      | 类型                                       | 必填   | 说明         |
166| -------- | ---------------------------------------- | ---- | ---------- |
167| builder  | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | 是    | 自定义组件构建函数。<br/>**说明:** 不支持全局builder。|
168| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt;      | 是    | 截图返回结果的回调。支持在回调中获取离屏组件绘制区域坐标和大小。 |
169
170**错误码:**
171
172| 错误码ID | 错误信息                                  |
173| -------- | ----------------------------------------- |
174| 100001   | if builder is not a valid build function. |
175
176**示例:**
177
178```ts
179import componentSnapshot from '@ohos.arkui.componentSnapshot'
180import image from '@ohos.multimedia.image'
181import componentUtils from '@ohos.arkui.componentUtils'
182
183@Entry
184@Component
185struct OffscreenSnapshotExample {
186  @State pixmap: image.PixelMap | undefined = undefined
187
188  @Builder
189  RandomBuilder() {
190    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
191      Text('Test menu item 1')
192        .fontSize(20)
193        .width(100)
194        .height(50)
195        .textAlign(TextAlign.Center)
196      Divider().height(10)
197      Text('Test menu item 2')
198        .fontSize(20)
199        .width(100)
200        .height(50)
201        .textAlign(TextAlign.Center)
202    }
203    .width(100)
204    .id("builder")
205  }
206
207  build() {
208    Column() {
209      Button("click to generate offscreen UI snapshot")
210        .onClick(() => {
211          componentSnapshot.createFromBuilder(()=>{this.RandomBuilder()},
212            (error: Error, pixmap: image.PixelMap) => {
213              if(error){
214                console.log("error: " + JSON.stringify(error))
215                return;
216              }
217              this.pixmap = pixmap
218              // save pixmap to file
219              // ....
220              // get component size and location
221              let info = componentUtils.getRectangleById("builder")
222              console.log(info.size.width + ' ' + info.size.height + ' ' + info.localOffset.x + ' ' + info.localOffset.y + ' ' + info.windowOffset.x + ' ' + info.windowOffset.y)
223            })
224        })
225      Image(this.pixmap)
226        .margin(10)
227        .height(200)
228        .width(200)
229        .border({ color: Color.Black, width: 2 })
230    }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
231  }
232}
233```
234
235![componentcreate](figures/componentcreate.gif)
236
237## componentSnapshot.createFromBuilder
238
239createFromBuilder(builder: CustomBuilder): Promise<image.PixelMap>
240
241在应用后台渲染CustomBuilder自定义组件,并输出其截图。通过Promise返回结果并支持获取离屏组件绘制区域坐标和大小。
242
243> **说明:**
244>
245> 由于需要等待组件构建、渲染成功,离屏截图的回调有500ms以内的延迟。
246>
247> 部分执行耗时任务的组件可能无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的[Image](arkui-ts/ts-basic-components-image.md)组件、[Web](../apis-arkweb/ts-basic-components-web.md)组件。
248
249**系统能力:** SystemCapability.ArkUI.ArkUI.Full
250
251**参数:**
252
253| 参数名     | 类型                                       | 必填   | 说明         |
254| ------- | ---------------------------------------- | ---- | ---------- |
255| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | 是    | 自定义组件构建函数。<br/>**说明:** 不支持全局builder。 |
256
257**返回值:**
258
259| 类型                            | 说明       |
260| ----------------------------- | -------- |
261| Promise&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | 截图返回的结果。 |
262
263**错误码:**
264
265| 错误码ID  | 错误信息                                     |
266| ------ | ---------------------------------------- |
267| 100001 | if builder is not a valid build function. |
268
269**示例:**
270
271```ts
272import componentSnapshot from '@ohos.arkui.componentSnapshot'
273import image from '@ohos.multimedia.image'
274import componentUtils from '@ohos.arkui.componentUtils'
275
276@Entry
277@Component
278struct OffscreenSnapshotExample {
279  @State pixmap: image.PixelMap | undefined = undefined
280
281  @Builder
282  RandomBuilder() {
283    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
284      Text('Test menu item 1')
285        .fontSize(20)
286        .width(100)
287        .height(50)
288        .textAlign(TextAlign.Center)
289      Divider().height(10)
290      Text('Test menu item 2')
291        .fontSize(20)
292        .width(100)
293        .height(50)
294        .textAlign(TextAlign.Center)
295    }
296    .width(100)
297    .id("builder")
298  }
299
300  build() {
301    Column() {
302      Button("click to generate offscreen UI snapshot")
303        .onClick(() => {
304          componentSnapshot.createFromBuilder(()=>{this.RandomBuilder()})
305            .then((pixmap: image.PixelMap) => {
306              this.pixmap = pixmap
307              // save pixmap to file
308              // ....
309              // get component size and location
310              let info = componentUtils.getRectangleById("builder")
311              console.log(info.size.width + ' ' + info.size.height + ' ' + info.localOffset.x + ' ' + info.localOffset.y + ' ' + info.windowOffset.x + ' ' + info.windowOffset.y)
312            }).catch((err:Error) => {
313            console.log("error: " + err)
314          })
315        })
316      Image(this.pixmap)
317        .margin(10)
318        .height(200)
319        .width(200)
320        .border({ color: Color.Black, width: 2 })
321    }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
322  }
323}
324```
325
326![componentcreate](figures/componentcreate.gif)