HarmonyOS 如何将当前视图组件保存为图片并保存呢?

如题:HarmonyOS 如何将当前视图组件保存为图片并保存呢?

阅读 603
1 个回答

可以用组件截图,文档如下:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-arkui-componentsnapshot-V5

import componentSnapshot from '@ohos.arkui.componentSnapshot' 
import image from '@ohos.multimedia.image' 
@Entry 
@Component 
struct waterMarkPage { 
  @State pixmap: image.PixelMap | undefined = undefined 
  build() { 
    Column() { 
      Stack({ alignContent: Alignment.Center }){ 
        Image($r('app.media.ic_product02')).autoResize(true).width(300).height(300) 
        Row() { 
          Text("水印").width(40).height(20).fontSize(16).fontColor(Color.White) 
            .border({ color: Color.Red, width: 1 }).borderRadius(4) 
            .margin({top:10,right:10}) 
        } 
        .width(300).height(300) 
        .alignItems(VerticalAlign.Top) 
        .justifyContent(FlexAlign.End) 
        Row() { 
          Image($r('app.media.startIcon')).autoResize(true).width(40).height(40).margin({bottom:10,right:10}) 
        } 
        .width(300).height(300) 
        .alignItems(VerticalAlign.Bottom) 
        .justifyContent(FlexAlign.End) 
      } 
      .id("root") 
      Button("生成水印图片") 
        .onClick(() => { 
          componentSnapshot.get("root") 
            .then((pixmap: image.PixelMap) => { 
              this.pixmap = pixmap 
            }).catch((err:Error) => { 
            console.log("error: " + err) 
          }) 
        }).margin(10) 
      Image(this.pixmap).width(300).height(300).border({ color: Color.Blue, width: 1 }).margin(5) 
    } 
    .width('100%') 
    .height('100%') 
    .alignItems(HorizontalAlign.Center) 
  } 
}

pixelMap保存到相册:

async imageWriteAlbumExample(pixelMap:image.PixelMap) { 
  console.info('createAssetDemo'); 
  let context = getContext(this); 
  let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); 
  let photoType: photoAccessHelper.PhotoType = photoAccessHelper.PhotoType.IMAGE; 
  let extension:string = 'jpg'; 
  let options: photoAccessHelper.CreateOptions = { 
    title: 'testPhoto' 
  } 
  let uri = await phAccessHelper.createAsset(photoType, extension, options); 
  try { 
      // 方式:通过imagePacker写入文件 
      let file: fs.File = fs.openSync(uri, fs .OpenMode.WRITE_ONLY); 
      let imagePacker: image.ImagePacker = image.createImagePacker(); 
      let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 100 }; 
      await imagePacker.packToFile(pixelMap , file.fd, packOpts); 
      fs.closeSync(file); 
      promptAction.showToast({ 
        message: '已保存至相册', 
        duration: 2500 
     }); 
  } 
  catch (err) { 
    console.error("error is "+ JSON.stringify(err)) 
    promptAction.showToast({ 
      message: '保存失败', 
      duration: 2000 
    }); 
  } 
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进