【HarmonyOS】鸿蒙应用实现截屏

【HarmonyOS】鸿蒙应用实现截屏

组件截屏


通过componentSnapshot的get函数,将需要截图的组件设置id传进去即可。

dart 复制代码
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("app.media.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直接获取图片。效率更高些。

dart 复制代码
  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}`);
    });
  }

关于如何屏蔽截屏行为,参见这篇文章。设置当前需要屏蔽截屏业务的容器窗口为,隐私窗口即可。【HarmonyOS】应用屏蔽截屏和录屏

相关推荐
若兰幽竹4 小时前
【鸿蒙HarmonyOS NEXT】UIAbility的生命周期
harmonyos
yiyiy111yiy7 小时前
关于HarmonyOS的学习
前端·javascript·学习·华为·harmonyos
谢道韫6668 小时前
HarmonyOs DevEco Studio小技巧8--string的用法
开发语言·harmonyos
jmoych11 小时前
解码数字化转型顶层规划(附236页PPT:xx企业数字化转型项目顶层规划方案)
安全·华为·制造
Android技术栈13 小时前
鸿蒙(API 12 Beta6版)GPU加速引擎服务【空域AI超分】
人工智能·华为·ai·harmonyos·鸿蒙·鸿蒙系统·openharmony
Android技术栈13 小时前
鸿蒙(API 12 Beta6版)超帧功能开发【ABR功能开发】
华为·移动开发·harmonyos·鸿蒙·鸿蒙系统·openharmony·abr
Android技术栈16 小时前
鸿蒙(API 12 Beta6版)【ArkGraphics 3D资源创建以及使用】方舟3D图形
3d·华为·harmonyos·鸿蒙·鸿蒙系统·openharmony·图形
让开,我要吃人了1 天前
HarmonyOS开发实战( Beta5版)状态管理优秀实践
android·前端·华为·移动开发·harmonyos·鸿蒙·鸿蒙开发
让开,我要吃人了1 天前
HarmonyOS开发实战( Beta5.0)系统提供的接口实践规范
linux·前端·华为·移动开发·harmonyos·鸿蒙·鸿蒙系统