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