【鸿蒙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));
              }
            })
          }
        }
      })
    }
  }
}
相关推荐
想成为高手49925 分钟前
华为仓颉编程语言的函数与结构类型分析
开发语言·华为
JasonYin~2 小时前
HarmonyOS NEXT 实战之元服务:静态案例效果---我的快递查询
harmonyos
nemo2012_20203 小时前
VisualRules华为应用场景介绍
华为·规则引擎·财务系统·财经系统
深海的鲸同学 luvi6 小时前
【HarmonyOS NEXT】鸿蒙原生应用“上述”
华为·harmonyos
play_big_knife6 小时前
鸿蒙项目云捐助第二十八讲云捐助项目首页组件云数据库加载轮播图
数据库·华为·harmonyos·鸿蒙·云开发·鸿蒙开发·鸿蒙技术
李洋-蛟龙腾飞公司12 小时前
HarmonyOS Next 应用元服务开发-应用接续动态配置迁移按需迁移页面
华为·harmonyos
JasonYin~12 小时前
HarmonyOS NEXT 实战之元服务:静态案例效果---查看手机历史记录
华为·harmonyos
鸿蒙程序媛12 小时前
2024最新鸿蒙开发面试题合集(二)-HarmonyOS NEXT Release(API 12 Release)
harmonyos·harmonyos面试题
No Silver Bullet13 小时前
HarmonyOS NEXT开发进阶(五):装饰器讲解
华为·harmonyos
塞尔维亚大汉14 小时前
【OpenHarmony】 鸿蒙 UI开发之MultiType
harmonyos·arkui