【HarmonyOS NEXT】鸿蒙应用实现截屏
组件截屏

通过componentSnapshot的get函数,将需要截图的组件设置id传进去即可。
import { componentSnapshot } from '@kit.ArkUI'; import { image } from '@kit.ImageKit'; /** * 截图 */ @Entry @Component @Preview struct SnapShotPage { @State mImageSnapShot: image.PixelMap | null = null; @Styles ImgStyle(){ .size({ width: px2vp(350), height: px2vp(350) }) } build() { Column(){ Blank() // 参照图片 Image($r(".icon_img")) .ImgStyle() .id("target") .autoResize(true) Blank() // 展示截图 Image(this.mImageSnapShot) .ImgStyle() .backgroundColor(Color.Blue) Blank() Button("点击截图参照图片控件") .onClick(()=>{ componentSnapshot.get("target", (error: Error, pixmap: image.PixelMap)=>{ if (error) { console.log("SnapShotDebug", "error: " + JSON.stringify(error)); return; } console.log("SnapShotDebug", "pixmap: " + JSON.stringify(pixmap)); this.mImageSnapShot = pixmap; }); }) Blank() } .size({ width: "100%", height: "100%" }) } }
示例效果请以真机运行为准,当前 IDE 预览器不支持。
流媒体截屏
对于使用XComponent的场景,例如:Video或者相机流媒体展示类组件,不建议使用组件截图相关接口,建议从surface直接获取图片。效率更高些。
private cutImage(surfaceId: string){
let region: image.Region = {
x: 0,
y: 0,
size:
{
height: 100,
width: 100
}
};
image.createPixelMapFromSurface(surfaceId, region).then(() => {
console.info("SnapShotDebug", 'Succeeded in creating pixelmap from Surface');
}).catch((error: BusinessError) => {
console.error("SnapShotDebug", `Failed to create pixelmap. code is ${error.code}, message is ${error.message}`);
});
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/24984661/viewspace-3107433/ ,如需转载,请注明出处,否则将追究法律责任。