鸿蒙5.0版开发:UI界面-@ohos.arkui.componentSnapshot (组件截图) ...

打印 上一主题 下一主题

主题 1025|帖子 1025|积分 3075

往期鸿蒙全套实战文章必看:



  • 鸿蒙开发焦点知识点,看这篇文章就够了
  • 最新版!鸿蒙HarmonyOS Next应用开发实战学习门路
  • 鸿蒙HarmonyOS NEXT开发技能最全学习门路指南
  • 鸿蒙应用开发实战项目,看这一篇文章就够了(部门项目附源码)

@ohos.arkui.componentSnapshot (组件截图)

本模块提供获取组件截图的能力,包罗已加载的组件的截图和没有加载的组件的截图。组件截图只能够截取组件大小的区域,假如组件的绘制超出了它的区域,或子组件的绘制超出了父组件的区域,这些在组件区域外绘制的内容不会在截图中出现。兄弟节点堆叠在组件区域内,截图不会表现兄弟组件。
   阐明:
  本模块首批接口从 API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
  对于使用XComponent的场景,例如:Video或者相机流媒体展示类组件,不发起使用组件截图相关接口,发起从surface直接获取图片。
  假如组件自身内容不能填满组件大小区域,那么剩余位置截图返回的内容为透明像素。假如组件使用了图像结果类属性或其他的结果类属性,则大概产生非用户预期的截图结果。请排查是否需要填充组件透明内容区域,或使用窗口截图替换。
  示例结果请以真机运行为准,当前 IDE 预览器不支持。
  导入模块

  1. import { componentSnapshot } from '@kit.ArkUI';
复制代码
componentSnapshot.get

get(id: string, callback: AsyncCallback<image.PixelMap>, options?: SnapshotOptions): void
获取已加载的组件的截图,传入组件的组件标识,找到对应组件举行截图。通过回调返回结果。
   阐明:
  截图会获取迩来一帧的绘制内容。假如在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。
  原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
体系能力: SystemCapability.ArkUI.ArkUI.Full
参数:
参数名范例必填阐明idstring是目的组件的组件标识callbackAsyncCallback<image.PixelMap>是截图返回结果的回调。options12+SnapshotOptions否截图相关的自定义参数。 错误码:
以下错误码的具体介绍。
错误码ID错误信息401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.100001Invalid ID. 示例:
   阐明:
  直接使用componentSnapshot大概导致实例不明确的题目,发起使用getUIContext获取UIContext实例,并使用getComponentSnapshot获取绑定实例的componentSnapshot。
  1. import { componentSnapshot } from '@kit.ArkUI';
  2. import { image } from '@kit.ImageKit';@Entry@Componentstruct SnapshotExample {  @State pixmap: image.PixelMap | undefined = undefined  build() {    Column() {      Row() {        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)        Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root")      }      Button("click to generate UI snapshot")        .onClick(() => {          // 发起使用this.getUIContext().getComponentSnapshot().get()          componentSnapshot.get("root", (error: Error, pixmap: image.PixelMap) => {            if (error) {              console.log("error: " + JSON.stringify(error))              return;            }            this.pixmap = pixmap          }, {scale : 2, waitUntilRenderFinished : true})        }).margin(10)    }    .width('100%')    .height('100%')    .alignItems(HorizontalAlign.Center)  }}
复制代码

componentSnapshot.get

get(id: string, options?: SnapshotOptions): Promise<image.PixelMap>
获取已加载的组件的截图,传入组件的组件标识,找到对应组件举行截图。通过Promise返回结果。
   阐明:
  截图会获取迩来一帧的绘制内容。假如在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。
  原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
体系能力: SystemCapability.ArkUI.ArkUI.Full
参数:
参数名范例必填阐明idstring是目的组件的组件标识options12+SnapshotOptions否截图相关的自定义参数。 返回值:
范例阐明Promise<image.PixelMap>截图返回的结果。 错误码:
以下错误码的具体介绍。
错误码ID错误信息401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.100001Invalid ID. 示例:
   阐明:
  直接使用componentSnapshot大概导致实例不明确的题目,发起使用getUIContext获取UIContext实例,并使用getComponentSnapshot获取绑定实例的componentSnapshot。
  1. import { componentSnapshot } from '@kit.ArkUI';
  2. import { image } from '@kit.ImageKit';@Entry@Componentstruct SnapshotExample {  @State pixmap: image.PixelMap | undefined = undefined  build() {    Column() {      Row() {        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)        Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root")      }      Button("click to generate UI snapshot")        .onClick(() => {          // 发起使用this.getUIContext().getComponentSnapshot().get()          componentSnapshot.get("root", {scale : 2, waitUntilRenderFinished : true})            .then((pixmap: image.PixelMap) => {              this.pixmap = pixmap            }).catch((err:Error) => {            console.log("error: " + err)          })        }).margin(10)    }    .width('100%')    .height('100%')    .alignItems(HorizontalAlign.Center)  }}
复制代码

componentSnapshot.createFromBuilder

createFromBuilder(builder: CustomBuilder, callback: AsyncCallback<image.PixelMap>, delay?: number, checkImageStatus?: boolean, options?: SnapshotOptions): void
在应用配景渲染CustomBuilder自定义组件,并输出其截图。通过回调返回结果并支持在回调中获取离屏组件绘制区域坐标和大小。
   阐明:
  由于需要等待组件构建、渲染成功,离屏截图的回调有500ms以内的延迟。
  部门执行耗时任务的组件大概无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的Image组件、Web组件。
  原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
体系能力: SystemCapability.ArkUI.ArkUI.Full
参数:
参数名范例必填阐明builderCustomBuilder是自定义组件构建函数。
阐明: 不支持全局builder。callbackAsyncCallback<image.PixelMap>是截图返回结果的回调。支持在回调中获取离屏组件绘制区域坐标和大小。delay12+number否指定触发截图指令的延迟时间。当结构中使用了图片组件时,需要指定延迟时间,以便体系解码图片资源。资源越大,解码需要的时间越长,发起尽量使用不需要解码的PixelMap资源。
当使用PixelMap资源或对Image组件设置syncload为true时,可以设置delay为0,逼迫不等待触发截图。该延迟时间并非指接口从调用到返回的时间,由于体系需要对传入的builder举行临时离屏构建,因此返回的时间通常要比该延迟时间长。
阐明: 截图接口传入的builder中,不应使用状态变量控制子组件的构建,假如必须要使用,在调用截图接口时,也不应再有厘革,以避免出现截图不符合预期的情况。
默认值:300
单位:毫秒checkImageStatus12+boolean否指定是否答应在截图之前,校验图片解码状态。假如为true,则会在截图之前查抄全部Image组件是否已经解码完成,假如没有完成查抄,则会放弃截图并返回非常。
默认值:falseoptions12+SnapshotOptions否截图相关的自定义参数。 错误码:
以下错误码的具体介绍。
错误码ID错误信息401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.100001The builder is not a valid build function.160001An 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. 示例:
   阐明:
  直接使用componentSnapshot大概导致实例不明确的题目,发起使用getUIContext获取UIContext实例,并使用getComponentSnapshot获取绑定实例的componentSnapshot。
  1. import { componentSnapshot } from '@kit.ArkUI';
  2. import { image } from '@kit.ImageKit';@Entry@Componentstruct OffscreenSnapshotExample {  @State pixmap: image.PixelMap | undefined = undefined  @Builder  RandomBuilder() {    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {      Text('Test menu item 1')        .fontSize(20)        .width(100)        .height(50)        .textAlign(TextAlign.Center)      Divider().height(10)      Text('Test menu item 2')        .fontSize(20)        .width(100)        .height(50)        .textAlign(TextAlign.Center)    }    .width(100)    .id("builder")  }  build() {    Column() {      Button("click to generate offscreen UI snapshot")        .onClick(() => {          // 发起使用this.getUIContext().getComponentSnapshot().createFromBuilder()          componentSnapshot.createFromBuilder(()=>{this.RandomBuilder()},            (error: Error, pixmap: image.PixelMap) => {              if(error){                console.log("error: " + JSON.stringify(error))                return;              }              this.pixmap = pixmap              // save pixmap to file              // ....              // get component size and location              let info = this.getUIContext().getComponentUtils().getRectangleById("builder")              console.log(info.size.width + ' ' + info.size.height + ' ' + info.localOffset.x + ' ' + info.localOffset.y + ' ' + info.windowOffset.x + ' ' + info.windowOffset.y)            }, 320, true, {scale : 2, waitUntilRenderFinished : true})        })      Image(this.pixmap)        .margin(10)        .height(200)        .width(200)        .border({ color: Color.Black, width: 2 })    }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)  }}
复制代码

componentSnapshot.createFromBuilder

createFromBuilder(builder: CustomBuilder, delay?: number, checkImageStatus?: boolean, options?: SnapshotOptions): Promise<image.PixelMap>
在应用配景渲染CustomBuilder自定义组件,并输出其截图。通过Promise返回结果并支持获取离屏组件绘制区域坐标和大小。
   阐明:
  由于需要等待组件构建、渲染成功,离屏截图的回调有500ms以内的延迟。
  部门执行耗时任务的组件大概无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的Image组件、Web组件。
  原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
体系能力: SystemCapability.ArkUI.ArkUI.Full
参数:
参数名范例必填阐明builderCustomBuilder是自定义组件构建函数。
阐明: 不支持全局builder。delay12+number否指定触发截图指令的延迟时间。当结构中使用了图片组件时,需要指定延迟时间,以便体系解码图片资源。资源越大,解码需要的时间越长,发起尽量使用不需要解码的PixelMap资源。
当使用PixelMap资源或对Image组件设置syncload为true时,可以设置delay为0,逼迫不等待触发截图。该延迟时间并非指接口从调用到返回的时间,由于体系需要对传入的builder举行临时离屏构建,因此返回的时间通常要比该延迟时间长。
阐明: 截图接口传入的builder中,不应使用状态变量控制子组件的构建,假如必须要使用,在调用截图接口时,也不应再有厘革,以避免出现截图不符合预期的情况。
默认值:300
单位:毫秒checkImageStatus12+boolean否指定是否答应在截图之前,校验图片解码状态。假如为true,则会在截图之前查抄全部Image组件是否已经解码完成,假如没有完成查抄,则会放弃截图并返回非常。
默认值:falseoptions12+SnapshotOptions否截图相关的自定义参数。 返回值:
范例阐明Promise<image.PixelMap>截图返回的结果。 错误码: 以下错误码的具体介绍。
错误码ID错误信息401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.100001The builder is not a valid build function.160001An 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. 示例:
   阐明:
  直接使用componentSnapshot大概导致实例不明确的题目,发起使用getUIContext获取UIContext实例,并使用getComponentSnapshot获取绑定实例的componentSnapshot。
  1. import { componentSnapshot } from '@kit.ArkUI'
  2. import { image } from '@kit.ImageKit'
  3. @Entry
  4. @Component
  5. struct OffscreenSnapshotExample {
  6.   @State pixmap: image.PixelMap | undefined = undefined
  7.   @Builder
  8.   RandomBuilder() {
  9.     Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  10.       Text('Test menu item 1')
  11.         .fontSize(20)
  12.         .width(100)
  13.         .height(50)
  14.         .textAlign(TextAlign.Center)
  15.       Divider().height(10)
  16.       Text('Test menu item 2')
  17.         .fontSize(20)
  18.         .width(100)
  19.         .height(50)
  20.         .textAlign(TextAlign.Center)
  21.     }
  22.     .width(100)
  23.     .id("builder")
  24.   }
  25.   build() {
  26.     Column() {
  27.       Button("click to generate offscreen UI snapshot")
  28.         .onClick(() => {
  29.           // 建议使用this.getUIContext().getComponentSnapshot().createFromBuilder()
  30.           componentSnapshot.createFromBuilder(()=>{this.RandomBuilder()}, 320, true, {scale : 2, waitUntilRenderFinished : true})
  31.             .then((pixmap: image.PixelMap) => {
  32.               this.pixmap = pixmap
  33.               // save pixmap to file
  34.               // ....
  35.               // get component size and location
  36.               let info = this.getUIContext().getComponentUtils().getRectangleById("builder")
  37.               console.log(info.size.width + ' ' + info.size.height + ' ' + info.localOffset.x + ' ' + info.localOffset.y + ' ' + info.windowOffset.x + ' ' + info.windowOffset.y)
  38.             }).catch((err:Error) => {
  39.             console.log("error: " + err)
  40.           })
  41.         })
  42.       Image(this.pixmap)
  43.         .margin(10)
  44.         .height(200)
  45.         .width(200)
  46.         .border({ color: Color.Black, width: 2 })
  47.     }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
  48.   }
  49. }
复制代码

componentSnapshot.getSync12+

getSync(id: string, options?: SnapshotOptions): image.PixelMap
获取已加载的组件的截图,传入组件的组件标识,找到对应组件举行截图。同步等待截图完成返回PixelMap。
   阐明:
  截图会获取迩来一帧的绘制内容。假如在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。
  原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
体系能力: SystemCapability.ArkUI.ArkUI.Full
参数:
参数名范例必填阐明idstring是目的组件的组件标识optionsSnapshotOptions否截图相关的自定义参数。 返回值:
范例阐明image.PixelMap截图返回的结果。 错误码:
以下错误码的具体介绍。
错误码ID错误信息401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.100001Invalid ID.160002Timeout. 示例:
   阐明:
  直接使用componentSnapshot大概导致实例不明确的题目,发起使用getUIContext获取UIContext实例,并使用getComponentSnapshot获取绑定实例的componentSnapshot。
  1. import { componentSnapshot } from '@kit.ArkUI';
  2. import { image } from '@kit.ImageKit';@Entry@Componentstruct SnapshotExample {  @State pixmap: image.PixelMap | undefined = undefined  build() {    Column() {      Row() {        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)        Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root")      }      Button("click to generate UI snapshot")        .onClick(() => {          try {          // 发起使用this.getUIContext().getComponentSnapshot().getSync()            let pixelmap = componentSnapshot.getSync("root", {scale : 2, waitUntilRenderFinished : true})            this.pixmap = pixelmap          } catch (error) {            console.error("getSync errorCode: " + error.code + " message: " + error.message)          }        }).margin(10)    }    .width('100%')    .height('100%')    .alignItems(HorizontalAlign.Center)  }}
复制代码

SnapshotOptions12+

体系能力: SystemCapability.ArkUI.ArkUI.Full
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
名称范例必填阐明scalenumber否指定截图时图形侧绘制pixelmap的缩放比例,比例过大时截图时间会变长,或者截图大概会失败。
默认值:1
阐明:
请不要截取过大尺寸的图片,截图不发起超过屏幕尺寸的大小。当要截取的图片目的长宽超过底层限定时,截图会返回失败,不同装备的底层限定不同。waitUntilRenderFinishedboolean否指定是否逼迫等待体系执行截图指令前全部绘制指令都执行完成之后再截图。该选项可尽大概确保截图内容是最新的状态,应尽量开启,要注意的是,开启后接口大概需要更长的时间返回,具体的时间依靠页面其时时候需要重绘区域的多少。
默认值:false



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

tsx81429

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表