【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】应用屏蔽截屏和录屏

相关推荐
whysqwhw1 小时前
鸿蒙freezeWhenInactive性能优化
harmonyos
monster_风铃10 小时前
华为实验NAT
华为
Fanmeang14 小时前
MPLS LDP概述
运维·网络·华为·路由·mpls·标签·ldp
熬了夜的程序员14 小时前
【华为机试】208. 实现 Trie (前缀树)
数据结构·算法·华为od·华为
何阿苗19 小时前
开发者技术支持-鸿蒙弹窗开发技术问题总结
harmonyos
zhanshuo21 小时前
跨设备开发不再难:HarmonyOS 分布式任务管理应用全解析
harmonyos
zhanshuo1 天前
鸿蒙本地与云端数据双向同步实战:从原理到可运行 Demo 的全流程指南
harmonyos
张风捷特烈1 天前
鸿蒙纪·Flutter卷#02 | 已有 Flutter 项目鸿蒙化 · 3.27.4 版
android·flutter·harmonyos
humors2211 天前
鸿蒙示例代码使用心得
华为·实战·harmonyos·鸿蒙·项目·huawei·实操
l and1 天前
Jenkins 搭建鸿蒙打包
jenkins·harmonyos