【鸿蒙NEXT】SaveButton保存图片

使用:

typescript 复制代码
QDSaveImageWindow.show({ message: str })

QDSaveImageWindowContent:

typescript 复制代码
let storage = LocalStorage.getShared()

@Entry(storage)
@Component
struct QDSaveImageWindowContent {
  @LocalStorageProp('model') model: QDAlertViewParams = new QDAlertViewParams()
  @State base64Str: string = ''
  @State windowScale: ScaleOptions = { x: 0, y: 0 }
  private bufferArray: ArrayBuffer = new ArrayBuffer(0)

  aboutToAppear() {
    this.base64Str = QDStringUtils.safeString(this.model.message)
    new util.Base64Helper().decode(this.base64Str).then((arr) => {
      if (arr && arr.length > 0) {
        this.bufferArray = QDStringUtils.uint8ArrayToArrayBuffer(arr)
      }
    })
  }

  onPageShow(): void {
    setTimeout(() => {
      this.windowScale = { x: 1, y: 1 }
    })
  }

  build() {
    Stack({ alignContent: Alignment.Center }) {
      Column() {
        Row() {
          Blank().width(35)
          Text('图片预览')
            .fontSize(18)
            .fontWeight('bold')
            .fontFamily(QDFontFamily.sansMedium)
            .height(44)
            .textAlign(TextAlign.Center)
            .fontColor($r('app.color.common_text_black_color'))
          Image($r('app.media.sms_close')).width(15).height(15).margin({ right: 20 })
            .onClick(() => {
              this.windowScale = { x: 0, y: 0 }
              setTimeout(() => {
                QDSaveImageWindow.hide()
              }, QDUIConstants.ALERT_ANIMATION_TIME)
            })
        }.width('100%').justifyContent(FlexAlign.SpaceBetween)

        Image(`data:image/png;base64,${this.base64Str}`)
          .width(200)
          .height(200)
          .align(Alignment.Center)
          .margin({ top: 16, bottom: 16 })
          .objectFit(ImageFit.Contain)

        QDLineComponent()
        SaveButton({ icon: SaveIconStyle.FULL_FILLED, buttonType: ButtonType.Capsule, text: SaveDescription.SAVE_IMAGE })
          .onClick((event: ClickEvent, result: SaveButtonOnClickResult) => {
            if (result == SaveButtonOnClickResult.SUCCESS) {
              try {
                this.windowScale = { x: 0, y: 0 }
                setTimeout(async () => {
                  QDSaveImageWindow.hide()
                  if (this.bufferArray.byteLength > 0) {
                    try {
                      if (this.bufferArray && this.bufferArray.byteLength > 0) {
                        let context = getContext() as common.UIAbilityContext
                        let helper = photoAccessHelper.getPhotoAccessHelper(context)
                        let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'png');
                        let file = await fs.open(uri, fs.OpenMode.WRITE_ONLY | fs.OpenMode.CREATE);
                        await fs.write(file.fd, this.bufferArray)
                        await fs.close(file.fd);
                        QDToastView.show('保存成功')
                      }else{
                        QDToastView.show('保存失败')
                      }
                    } catch (err) {
                      QDToastView.show('保存失败')
                    }
                  }
                }, QDUIConstants.ALERT_ANIMATION_TIME)
              } catch (error) {
                QDToastView.show('保存失败')
                QDLogUtils.error("error is " + JSON.stringify(error));
              }
            }
          }).width('90%').height(40)

        Blank().height(16)
      } //Column
      .borderWidth(QDDeviceInfoUtils.lineScale())
      .borderColor($r('app.color.keyboard_bg_gray_color'))
      .borderRadius(QDUIConstants.BORDER_RADIUS)
      .width(QDDeviceInfoUtils.screenWidth() - 32 * 2)
      .offset({ y: -50 })
      .backgroundColor(Color.White)
      .scale(this.windowScale)
      .animation({
        duration: QDUIConstants.ALERT_ANIMATION_TIME,
        curve: Curve.FastOutSlowIn,
        iterations: 1,
        playMode: PlayMode.Normal
      })

    }.width('100%')
    .height('100%')
    .backgroundColor(Color.Transparent)
  }
}

QDSaveImageWindow

typescript 复制代码
export class QDSaveImageWindow {
  private static windowClass: window.Window;

  // 自定义创建悬浮窗方法
  static show(model: QDAlertViewParams) {
    try {
      QDSaveImageWindow.windowClass = window.findWindow("QDSaveImageWindow")
      if (QDSaveImageWindow.windowClass) {
        QDSaveImageWindow.loadContent(model)
      } else {
        QDSaveImageWindow.createWindow(model)
      }
    } catch (e) {
      QDSaveImageWindow.createWindow(model)
    }
  }

  private static createWindow(model: QDAlertViewParams) {
    EntryAbility.windowStage.createSubWindow('QDSaveImageWindow', (_err, data) => {
      QDSaveImageWindow.windowClass = data
      QDSaveImageWindow.loadContent(model)
    })
  }

  static hide(callback?: () => void) {
    try {
      if (!QDSaveImageWindow.windowClass) {
        QDSaveImageWindow.windowClass = window.findWindow("QDSaveImageWindow")
      }
      if (QDSaveImageWindow.windowClass) {
        QDSaveImageWindow.windowClass.destroyWindow(callback)
      }
    } catch (err) {
      QDLogUtils.error('QDSaveImageWindow Failed to change the window size. Cause:' + JSON.stringify(err));
    }
  }

  private static loadContent(model: QDAlertViewParams) {
    let storage: LocalStorage = new LocalStorage();
    storage.setOrCreate('model', model);
    if (QDSaveImageWindow.windowClass) {
      QDSaveImageWindow.windowClass.loadContent("pages/QDSaveImageWindowContent", storage, (err) => {
        if (err.code) {
          QDLogUtils.error('Failed to load the content. Cause:' + JSON.stringify(err));
        } else {
          if (QDSaveImageWindow.windowClass) {
            QDSaveImageWindow.windowClass.setWindowBackgroundColor('#B3000000')
            QDSaveImageWindow.windowClass.showWindow((err) => {
              if (err.code) {
                QDLogUtils.error('Failed to show the window. Cause: ' + JSON.stringify(err));
              }
            })
          }
        }
      })
    }
  }
}
相关推荐
ChinaDragonDreamer2 小时前
HarmonyOS:自定义组件冻结功能
开发语言·harmonyos·鸿蒙
雪芽蓝域zzs5 小时前
uni-app 运行HarmonyOS项目
uni-app·harmonyos
Bert.King6 小时前
<HarmonyOS第一课>给应用添加通知和提醒的习题
华为·harmonyos
法迪17 小时前
华为手机系统应用瘦身
华为·智能手机·功耗
觉醒法师19 小时前
HarmonyOS开发 - 本地持久化之实现LocalStorage支持多实例
前端·javascript·华为·typescript·harmonyos
东林知识库1 天前
2024年10月HarmonyOS应用开发者基础认证全新题库
学习·华为·harmonyos
ChinaDragonDreamer1 天前
HarmonyOS:@Watch装饰器:状态变量更改通知
开发语言·harmonyos·鸿蒙
Lei活在当下1 天前
【初探鸿蒙01】鸿蒙生态用开发白皮书V3.0解读
harmonyos
法迪1 天前
华为手机卸载系统应用的方法
华为·智能手机