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> 部分执行耗时任务的组件可能无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的[Image](arkui-ts/ts-basic-components-image.md)组件、[Web](../apis-arkweb/ts-basic-components-web.md)组件。 183 184**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 185 186**系统能力:** SystemCapability.ArkUI.ArkUI.Full 187 188**参数:** 189 190| 参数名 | 类型 | 必填 | 说明 | 191| -------- | ---------------------------------------- | ---- | ---------- | 192| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | 是 | 自定义组件构建函数。<br/>**说明:** 不支持全局builder。| 193| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | 是 | 截图返回结果的回调。支持在回调中获取离屏组件绘制区域坐标和大小。 | 194| delay<sup>12+</sup> | number | 否 | 指定触发截图指令的延迟时间。当布局中使用了图片组件时,需要指定延迟时间,以便系统解码图片资源。资源越大,解码需要的时间越长,建议尽量使用不需要解码的PixelMap资源。<br/> 当使用PixelMap资源或对Image组件设置syncload为true时,可以配置delay为0,强制不等待触发截图。该延迟时间并非指接口从调用到返回的时间,由于系统需要对传入的builder进行临时离屏构建,因此返回的时间通常要比该延迟时间长。<br/>**说明:** 截图接口传入的builder中,不应使用状态变量控制子组件的构建,如果必须要使用,在调用截图接口时,也不应再有变化,以避免出现截图不符合预期的情况。<br/> 默认值:300 <br/> 单位:毫秒| 195| checkImageStatus<sup>12+</sup> | boolean | 否 | 指定是否允许在截图之前,校验图片解码状态。如果为true,则会在截图之前检查所有Image组件是否已经解码完成,如果没有完成检查,则会放弃截图并返回异常。<br/>默认值:false| 196| options<sup>12+</sup> | [SnapshotOptions](#snapshotoptions12) | 否 | 截图相关的自定义参数。 | 197 198**错误码:** 199 200以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 201 202| 错误码ID | 错误信息 | 203| -------- | ------------------------------------------------------------ | 204| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 205| 100001 | The builder is not a valid build function. | 206| 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. | 207 208**示例:** 209 210> **说明:** 211> 212> 直接使用componentSnapshot可能导致实例不明确的问题,建议使用[getUIContext](js-apis-arkui-UIContext.md#uicontext)获取UIContext实例,并使用[getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12)获取绑定实例的componentSnapshot。 213 214```ts 215import { componentSnapshot } from '@kit.ArkUI'; 216import { image } from '@kit.ImageKit'; 217 218@Entry 219@Component 220struct OffscreenSnapshotExample { 221 @State pixmap: image.PixelMap | undefined = undefined 222 223 @Builder 224 RandomBuilder() { 225 Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { 226 Text('Test menu item 1') 227 .fontSize(20) 228 .width(100) 229 .height(50) 230 .textAlign(TextAlign.Center) 231 Divider().height(10) 232 Text('Test menu item 2') 233 .fontSize(20) 234 .width(100) 235 .height(50) 236 .textAlign(TextAlign.Center) 237 } 238 .width(100) 239 .id("builder") 240 } 241 242 build() { 243 Column() { 244 Button("click to generate offscreen UI snapshot") 245 .onClick(() => { 246 // 建议使用this.getUIContext().getComponentSnapshot().createFromBuilder() 247 componentSnapshot.createFromBuilder(()=>{this.RandomBuilder()}, 248 (error: Error, pixmap: image.PixelMap) => { 249 if(error){ 250 console.log("error: " + JSON.stringify(error)) 251 return; 252 } 253 this.pixmap = pixmap 254 // save pixmap to file 255 // .... 256 // get component size and location 257 let info = this.getUIContext().getComponentUtils().getRectangleById("builder") 258 console.log(info.size.width + ' ' + info.size.height + ' ' + info.localOffset.x + ' ' + info.localOffset.y + ' ' + info.windowOffset.x + ' ' + info.windowOffset.y) 259 }, 320, true, {scale : 2, waitUntilRenderFinished : true}) 260 }) 261 Image(this.pixmap) 262 .margin(10) 263 .height(200) 264 .width(200) 265 .border({ color: Color.Black, width: 2 }) 266 }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300) 267 } 268} 269``` 270 271 272 273## componentSnapshot.createFromBuilder 274 275createFromBuilder(builder: CustomBuilder, delay?: number, checkImageStatus?: boolean, options?: SnapshotOptions): Promise<image.PixelMap> 276 277在应用后台渲染CustomBuilder自定义组件,并输出其截图。通过Promise返回结果并支持获取离屏组件绘制区域坐标和大小。 278 279> **说明:** 280> 281> 由于需要等待组件构建、渲染成功,离屏截图的回调有500ms以内的延迟。 282> 283> 部分执行耗时任务的组件可能无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的[Image](arkui-ts/ts-basic-components-image.md)组件、[Web](../apis-arkweb/ts-basic-components-web.md)组件。 284 285**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 286 287**系统能力:** SystemCapability.ArkUI.ArkUI.Full 288 289**参数:** 290 291| 参数名 | 类型 | 必填 | 说明 | 292| ------- | ---------------------------------------- | ---- | ---------- | 293| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | 是 | 自定义组件构建函数。<br/>**说明:** 不支持全局builder。 | 294| delay<sup>12+</sup> | number | 否 | 指定触发截图指令的延迟时间。当布局中使用了图片组件时,需要指定延迟时间,以便系统解码图片资源。资源越大,解码需要的时间越长,建议尽量使用不需要解码的PixelMap资源。<br/> 当使用PixelMap资源或对Image组件设置syncload为true时,可以配置delay为0,强制不等待触发截图。该延迟时间并非指接口从调用到返回的时间,由于系统需要对传入的builder进行临时离屏构建,因此返回的时间通常要比该延迟时间长。<br/>**说明:** 截图接口传入的builder中,不应使用状态变量控制子组件的构建,如果必须要使用,在调用截图接口时,也不应再有变化,以避免出现截图不符合预期的情况。<br/> 默认值:300 <br/> 单位:毫秒| 295| checkImageStatus<sup>12+</sup> | boolean | 否 | 指定是否允许在截图之前,校验图片解码状态。如果为true,则会在截图之前检查所有Image组件是否已经解码完成,如果没有完成检查,则会放弃截图并返回异常。<br/>默认值:false| 296| options<sup>12+</sup> | [SnapshotOptions](#snapshotoptions12) | 否 | 截图相关的自定义参数。 | 297 298**返回值:** 299 300| 类型 | 说明 | 301| ----------------------------- | -------- | 302| Promise<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | 截图返回的结果。 | 303 304**错误码:** 305以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 306 307| 错误码ID | 错误信息 | 308| ------ | ---------------------------------------- | 309| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 310| 100001 | The builder is not a valid build function. | 311| 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. | 312 313**示例:** 314 315> **说明:** 316> 317> 直接使用componentSnapshot可能导致实例不明确的问题,建议使用[getUIContext](js-apis-arkui-UIContext.md#uicontext)获取UIContext实例,并使用[getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12)获取绑定实例的componentSnapshot。 318 319```ts 320import { componentSnapshot } from '@kit.ArkUI' 321import { image } from '@kit.ImageKit' 322 323@Entry 324@Component 325struct OffscreenSnapshotExample { 326 @State pixmap: image.PixelMap | undefined = undefined 327 328 @Builder 329 RandomBuilder() { 330 Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { 331 Text('Test menu item 1') 332 .fontSize(20) 333 .width(100) 334 .height(50) 335 .textAlign(TextAlign.Center) 336 Divider().height(10) 337 Text('Test menu item 2') 338 .fontSize(20) 339 .width(100) 340 .height(50) 341 .textAlign(TextAlign.Center) 342 } 343 .width(100) 344 .id("builder") 345 } 346 347 build() { 348 Column() { 349 Button("click to generate offscreen UI snapshot") 350 .onClick(() => { 351 // 建议使用this.getUIContext().getComponentSnapshot().createFromBuilder() 352 componentSnapshot.createFromBuilder(()=>{this.RandomBuilder()}, 320, true, {scale : 2, waitUntilRenderFinished : true}) 353 .then((pixmap: image.PixelMap) => { 354 this.pixmap = pixmap 355 // save pixmap to file 356 // .... 357 // get component size and location 358 let info = this.getUIContext().getComponentUtils().getRectangleById("builder") 359 console.log(info.size.width + ' ' + info.size.height + ' ' + info.localOffset.x + ' ' + info.localOffset.y + ' ' + info.windowOffset.x + ' ' + info.windowOffset.y) 360 }).catch((err:Error) => { 361 console.log("error: " + err) 362 }) 363 }) 364 Image(this.pixmap) 365 .margin(10) 366 .height(200) 367 .width(200) 368 .border({ color: Color.Black, width: 2 }) 369 }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300) 370 } 371} 372``` 373 374 375 376## componentSnapshot.getSync<sup>12+</sup> 377 378getSync(id: string, options?: SnapshotOptions): image.PixelMap 379 380获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。同步等待截图完成返回[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)。 381 382> **说明:** 383> 384> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。 385 386**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 387 388**系统能力:** SystemCapability.ArkUI.ArkUI.Full 389 390**参数:** 391 392| 参数名 | 类型 | 必填 | 说明 | 393| ---- | ------ | ---- | ---------------------------------------- | 394| id | string | 是 | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识) | 395| options | [SnapshotOptions](#snapshotoptions12) | 否 | 截图相关的自定义参数。 | 396 397**返回值:** 398 399| 类型 | 说明 | 400| ----------------------------- | -------- | 401| image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | 截图返回的结果。 | 402 403**错误码:** 404 405以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 406 407| 错误码ID | 错误信息 | 408| ------ | ------------------- | 409| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 410| 100001 | Invalid ID. | 411| 160002 | Timeout. | 412 413**示例:** 414 415> **说明:** 416> 417> 直接使用componentSnapshot可能导致实例不明确的问题,建议使用[getUIContext](js-apis-arkui-UIContext.md#uicontext)获取UIContext实例,并使用[getComponentSnapshot](js-apis-arkui-UIContext.md#getcomponentsnapshot12)获取绑定实例的componentSnapshot。 418 419```ts 420import { componentSnapshot } from '@kit.ArkUI'; 421import { image } from '@kit.ImageKit'; 422 423@Entry 424@Component 425struct SnapshotExample { 426 @State pixmap: image.PixelMap | undefined = undefined 427 428 build() { 429 Column() { 430 Row() { 431 Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5) 432 Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root") 433 } 434 Button("click to generate UI snapshot") 435 .onClick(() => { 436 try { 437 // 建议使用this.getUIContext().getComponentSnapshot().getSync() 438 let pixelmap = componentSnapshot.getSync("root", {scale : 2, waitUntilRenderFinished : true}) 439 this.pixmap = pixelmap 440 } catch (error) { 441 console.error("getSync errorCode: " + error.code + " message: " + error.message) 442 } 443 }).margin(10) 444 } 445 .width('100%') 446 .height('100%') 447 .alignItems(HorizontalAlign.Center) 448 } 449} 450``` 451 452 453 454## SnapshotOptions<sup>12+</sup> 455 456**系统能力:** SystemCapability.ArkUI.ArkUI.Full 457 458**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 459 460| 名称 | 类型 | 必填 | 说明 | 461| ---------------|------------ | -----------------------------| -----------------------------| 462| scale | number | 否 | 指定截图时图形侧绘制pixelmap的缩放比例,比例过大时截图时间会变长,或者截图可能会失败。 <br/> 默认值:1 <br/>**说明:** <br/>请不要截取过大尺寸的图片,截图不建议超过屏幕尺寸的大小。当要截取的图片目标长宽超过底层限制时,截图会返回失败,不同设备的底层限制不同。 | 463| waitUntilRenderFinished | boolean | 否 | 指定是否强制等待系统执行截图指令前所有绘制指令都执行完成之后再截图。该选项可尽可能确保截图内容是最新的状态,应尽量开启,要注意的是,开启后接口可能需要更长的时间返回,具体的时间依赖页面当时时刻需要重绘区域的多少。<br/> 默认值:false |