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

相关推荐
learning-striving36 分钟前
eNSP下载安装(eNsp、WinPcap、Wireshark、VirtualBox下载安装)
网络·计算机网络·华为·路由器·ensp·交换机
陈无左耳、1 小时前
HarmonyOS学习第4天: DevEco Studio初体验
学习·华为·harmonyos
月未央3 小时前
HarmonyOS Next 开发系列:Local 状态管理实践
harmonyos
openinstall全渠道统计16 小时前
免填邀请码工具:赋能六大核心场景,重构App增长新模型
android·ios·harmonyos
shaodong112316 小时前
鸿蒙系统-同应用跨设备数据同步(分布式功能)
分布式·华为·harmonyos
敢嗣先锋16 小时前
鸿蒙5.0实战案例:基于ImageKit对图片进行处理
移动开发·harmonyos·arkui·组件化·鸿蒙开发
陈无左耳、16 小时前
HarmonyOS学习第3天: 环境搭建开启鸿蒙开发新世界
学习·华为·harmonyos
敢嗣先锋16 小时前
鸿蒙5.0实战案例:基于ArkUI的验证码实现
移动开发·harmonyos·openharmony·arkui·鸿蒙开发
别说我什么都不会19 小时前
鸿蒙轻内核M核源码分析系列十二 事件Event
操作系统·harmonyos
Huang兄20 小时前
鸿蒙-canvas-刮刮乐
华为·harmonyos