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

相关推荐
心中有国也有家9 小时前
ArkTS 鸿蒙开发语法完全指南:从入门到实战
华为·harmonyos
Georgewu12 小时前
如何判断应用在鸿蒙卓易通或者出境易环境下?
android·harmonyos
菜鸟不学编程12 小时前
鸿蒙中的 AR/VR 开发与场景创建
ar·vr·harmonyos
平生幻13 小时前
华为防火墙-日志分析INFO/2/ICLogfileThreshold
华为
Swift社区14 小时前
鸿蒙应用上架流程经验
华为·harmonyos
@不误正业14 小时前
OpenHarmony集成AI Agent实战:打造鸿蒙智能助理
人工智能·华为·harmonyos
小资同学15 小时前
考研机试之递归与贪心算法
算法·华为·贪心算法
仓颉编程语言16 小时前
CangjieSkills 正式开源:为仓颉 AI 编程打造的“技能增强“方案,实测降低 60% 费用
华为·ai编程·鸿蒙·仓颉编程语言
弓.长.18 小时前
ReactNative for OpenHarmony项目鸿蒙化三方库:react-native-netinfo — 网络状态检测
网络·react native·harmonyos
弓.长.18 小时前
ReactNative for OpenHarmony项目鸿蒙化三方库:react-native-network-info — 网络信息获取
网络·react native·harmonyos