本模块提供获取组件截图的能力,包括已加载的组件的截图和没有加载的组件的截图。组件截图只能够截取组件大小的区域,如果组件的绘制超出了它的区域,或子组件的绘制超出了父组件的区域,这些在组件区域外绘制的内容不会在截图中呈现。兄弟节点堆叠在组件区域内,截图不会显示兄弟组件。
本模块首批接口从 API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
对于使用XComponent的场景,例如:Video或者相机流媒体展示类组件,不建议使用组件截图相关接口,建议从surface直接获取图片。
示例效果请以真机运行为准,当前 IDE 预览器不支持。
导入模块
import { componentSnapshot } from '@kit.ArkUI';
componentSnapshot.get
get(id: string, callback: AsyncCallback<image.PixelMap>): void
获取已加载的组件的截图,传入组件的组件标识,找到对应组件进行截图。通过回调返回结果。
说明
截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。
系统能力: SystemCapability.ArkUI.ArkUI.Full
参数:
参数名 | 类型 | 必填 | 说明 |
---|---|---|---|
id | string | 是 | 目标组件的组件标识 |
callback | AsyncCallback<image.PixelMap> | 是 | 截图返回结果的回调。 |
错误码:
以下错误码的详细介绍请参见通用错误码错误码。
错误码ID | 错误信息 |
---|---|
401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed. |
100001 | Invalid ID. |
示例:
import { componentSnapshot } from '@kit.ArkUI';
import { image } from '@kit.ImageKit';
@Entry
@Component
struct 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(() => {
componentSnapshot.get("root", (error: Error, pixmap: image.PixelMap) => {
if (error) {
console.log("error: " + JSON.stringify(error))
return;
}
this.pixmap = pixmap
})
}).margin(10)
}
.width('100%')
.height('100%')
.alignItems(HorizontalAlign.Center)
}
}