HarmonyOS 鸿蒙Next中如何实现窗口截屏

参考文档HarmonyOS 鸿蒙Next中想实现窗口截屏的功能,按照文档描述,window API 只能在 Ability 中使用而能在 pages 中使用

我暂时最直白的操作是等待窗口加载内容后进行截屏操作

function onWindowStageCreate(windowStage: window.WindowStage): void {
  // Main window is created, set main page for this ability
  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

  windowStage.loadContent('pages/Index', (err) => {
    if (err.code) {
      hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
      return;
    }
    hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
    const start = Date.now();
    while (Date.now() - start < 3000) {
      // 空循环,等待 1 秒
    }
    try {
      let windowClass: window.Window | undefined = undefined;
      let Wpromise = windowStage.getMainWindow();
      Wpromise.then((data) => {
        windowClass = data;
        console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data));
        windowClass.showWindow()
        let Spromise = windowClass.snapshot();

        let RecentPhotoPath: string;
        Spromise.then((pixelMap: image.PixelMap) => {
          console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber());
          try {
            if (this.applicationContext != null){
              RecentPhotoPath = this.applicationContext.cacheDir + "/WindowsPath.jpg";
              console.info('Succeeded in snapshotting window. RecentPhotoPath: ' + RecentPhotoPath);
            }

            const imagePackerApi: image.ImagePacker = image.createImagePacker();
            let file = fileIo.openSync(RecentPhotoPath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
            console.info('Succeeded in snapshotting window. Open File: ' + file);
            let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 };
            imagePackerApi.packToFile(pixelMap, file.fd, packOpts).then(() => {
              // 直接打包进文件
              console.info('Succeeded in snapshotting window. packToFile: ' + RecentPhotoPath);
            }).catch((error : BusinessError) => {
              console.error('Failed to pack the image. And the error is: ' + error);
            })
            pixelMap.release(); // PixelMap使用完后及时释放内存
          } catch (error) {
            console.error(`getApplicationContext failed, error.code: ${error.code}, error.message: ${error.message}`);
          }

        }).catch((err: BusinessError) => {
          console.error(`Failed to snapshot window. Cause code: ${err.code}, message: ${err.message}`);
        });
      }).catch((err: BusinessError) => {
        console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err));
      });

    } catch (exception) {
      console.error(`Failed to obtain the main window. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  });
}

目前的现象是,首先窗口是等待3秒后加载内容而不是加载后等待三秒进行截屏,因此截屏保留下来的照片总是纯黑色默认,我猜测是和同步异步函数相关,请问该 API 该如何使用,是应当监听事件,还是与 page 进行状态量通信


更多关于HarmonyOS 鸿蒙Next中如何实现窗口截屏的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

更多关于HarmonyOS 鸿蒙Next中如何实现窗口截屏的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,可以通过Window类的snapshot方法实现窗口截屏。首先获取当前窗口实例,然后调用snapshot方法生成截屏图像。示例代码如下:

Window window = getWindow();
Image image = window.snapshot();

snapshot方法返回一个Image对象,可以进一步保存或处理。确保在UI线程中调用此方法,以避免线程安全问题。

回到顶部