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

相关推荐
yuegu7772 分钟前
HarmonyOS应用<节气通>开发第6篇:节气详情页(下)——诗词与养生
华为·harmonyos
慧海灵舟13 分钟前
鸿蒙南向开发教程Day 2:创建自己的 Hello World 工程
华为·harmonyos·写文章,赢小鸿ai
颜淡慕潇1 小时前
鸿蒙 PC的 vcpkg 交叉编译库在x86_64宿主环境下的AI自动化验证方案
人工智能·自动化·harmonyos
再见6581 小时前
HarmonyOS NEXT 实战:从零开发一款密码生成器应用
华为·harmonyos
李二。2 小时前
鸿蒙原生ArkTS布局方式之ColumnBaseline垂直排列
华为·harmonyos
yuegu7772 小时前
HarmonyOS应用<节气通>开发第8篇:知识百科页开发
华为·harmonyos
想你依然心痛2 小时前
HarmonyOS 6(API 23)实战:基于悬浮导航、沉浸光感与HMAF的“航界智脑“——PC端AI智能体沉浸式无人机集群任务规划与空域协同管理工作台
人工智能·ar·无人机·harmonyos·智能体
李二。3 小时前
鸿蒙原生ArkTS布局方式之ColumnCenter垂直排列
华为·harmonyos
不爱吃糖的程序媛3 小时前
@capacitor/camera 插件在鸿蒙PC平台的适配实践
华为·harmonyos