【鸿蒙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));
              }
            })
          }
        }
      })
    }
  }
}
相关推荐
HarmonyOS_SDK3 小时前
【HarmonyOS SDK Skills】扫码能力一键构建,系统级高精度扫码秒实现
harmonyos
结局无敌6 小时前
React Native for OpenHarmony 实战:三方库 react-native-modal-dialog 的鸿蒙化适配指南
深度学习·算法·react native·react.js·harmonyos
hunterandroid7 小时前
HarmonyOS 长列表滚动性能优化:预渲染、离屏缓存与 GPU 合成策略
华为·前端框架
结局无敌8 小时前
React Native for OpenHarmony 实战:三方库 react-native-paper 的鸿蒙化适配指南
javascript·人工智能·深度学习·react native·react.js·ecmascript·harmonyos
七月稻草人8 小时前
鸿蒙手机远程控制电脑选哪个?2026 鸿蒙远控软件横评
智能手机·电脑·harmonyos
熊猫钓鱼>_>8 小时前
Kotlin Multiplatform for OpenHarmony 实战:kotlinx-coroutines 结构化并发适配
开发语言·kotlin·agent·harmonyos·openharmony·适配·华为云码道
结局无敌8 小时前
React Native for OpenHarmony 实战:三方库 react-native-progress-steps 的鸿蒙化适配指南
javascript·人工智能·深度学习·react native·react.js·harmonyos
熊猫钓鱼>_>10 小时前
Kotlin Multiplatform for OpenHarmony 实战:kotlinx-serialization JSON 适配
开发语言·华为·kotlin·华为云·json·harmonyos·code
马剑威(威哥爱编程)21 小时前
【共创稿事节】HarmonyOS 7 Agent 开发实战 11:并发多会话隔离
华为·harmonyos
行者-全栈开发1 天前
【共创稿事节】HarmonyOS 7 空间音频实战:用 AudioSpatializationManager 构建“听得见方位“的声场
harmonyos·arkts·鸿蒙·空间音频·api 26·audio kit