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

相关推荐
爱笑的眼睛1112 分钟前
深入浅出ArkTS:HarmonyOS应用开发的现代化语法解析
华为·harmonyos
INFINI Labs7 小时前
Elasticsearch 备份:snapshot 镜像使用篇
大数据·elasticsearch·搜索引擎·snapshot·backup
Kisang.9 小时前
【HarmonyOS】窗口管理实战指南
前端·华为·typescript·harmonyos·鸿蒙
犹若故人归10 小时前
华为ENSP——OSPF的基本配置实验
华为
it技术10 小时前
鸿蒙HarmonyOS实战开发系列课程
harmonyos
●VON12 小时前
重生之我在大学自学鸿蒙开发第一天-《基础篇》
学习·华为·harmonyos·鸿蒙
浅蓝色13 小时前
flutter平台判断后续
flutter·harmonyos
程序员潘Sir14 小时前
鸿蒙应用开发从入门到实战(二十):ArkUI内置弹窗组件
harmonyos·鸿蒙
旺仔Sec14 小时前
2025年江西省职业院校技能大赛高职组鸿蒙应用开发赛项竞赛任务书
华为·harmonyos