当前位置: 首页 > article >正文

HarmonyOS开发之使用Picker(从相册选择图片),并且通过Swiper组件实现图片预览

一:效果图:

二:添加依赖

import picker from '@ohos.file.picker';

三:创建showDialog

 showDialog() {
    AlertDialog.show({
      message: '从相册选择',
      alignment: DialogAlignment.Bottom,
      offset: { dx: 0, dy: -12 },
      primaryButton: {
        value: '取消',
        fontColor: '#0A59F7',
        action: () => {
        }
      },
      secondaryButton: {
        value: '确定',
        fontColor: '#0A59F7',
        action: () => {
          try {
            let photoSelectOptions = new picker.PhotoSelectOptions()
            photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE//文件类型
            photoSelectOptions.maxSelectNumber = 5// 单次选择壁纸数量
            let photoPicker = new picker.PhotoViewPicker()
            photoPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => {
              console.log("photoUris ====="+photoSelectResult.photoUris)
              this.addImages(photoSelectResult.photoUris)
            }).catch((err: string) => {
              console.error(TAG, `'PhotoViewPicker.select failed with err: ${JSON.stringify(err)}`)
            });
          } catch (err) {
            console.error(TAG, `'PhotoViewPicker failed with err: ${JSON.stringify(err)}`)
          }
        }
      }
    })
  }

四:通过Swiper来实现图片预览

Swiper(this.swiperController) {
          ForEach(this.imageList, (item: string) => {
            Image(item)
              .width('100%')
              .height('auto')
          }, item => item)
        }
        .cachedCount(2)
        .index(this.currentImageIndex) // 设置当前图片索引
        .autoPlay(false)
        .interval(4000)
        .indicator(true)
        .loop(true)
        .duration(1000)
        .itemSpace(0)
        .curve(Curve.Linear)
        .onClick(()=>{
          this.isSwiperVisible = false; // 关闭 Swiper
          this.isVisibility=Visibility.Visible
        })

五:完整代码

import picker from '@ohos.file.picker';

const TAG: string = 'AddPictures';

@Extend(Image) function imageStyle() {
  .width('100%')
  .aspectRatio(1)
  .objectFit(ImageFit.Fill)
  .backgroundColor('#F1F3F5')
  .borderRadius(12)
}

@Component
export struct AddPictures{
  @Provide imageList: Array<string> = []; // 定义并初始化 imageList

  @State isSwiperVisible: boolean = false; // 控制 Swiper 可见性
  @State currentImageIndex: number = 0; // 当前展示的图片索引
  @State isVisibility:Visibility=Visibility.Visible

  private swiperController: SwiperController = new SwiperController()

  build() {
    Column() {
      Text('有什么想说的就留言吧!...')
        .fontColor($r('app.color.text_color'))
        .fontWeight(400)
        .fontFamily('HarmonyHeiTi')
        .fontSize(14)
        .opacity(0.4)
        .margin({ top:'16vp', bottom: '48vp' })
        .width('100%')
        .visibility(this.isVisibility)
      GridRow({ columns: { sm: 3, md: 6, lg: 8 }, gutter: 12 }) {
        ForEach(this.imageList, (item: string,index:number) => {
          GridCol({ span: 1 }) {
            Image(item)
              .imageStyle()
              .onClick(()=>{
                console.log(TAG+'======'+item)
                this.currentImageIndex = index // 记录当前索引
                this.isSwiperVisible = true // 打开 Swiper
                this.isVisibility=Visibility.None
              })
          }
        })
        GridCol({ span: 1 }) {
          Row() {
            Image($r('app.media.ic_add'))
              .size({ width: 24, height: 24 })
              .objectFit(ImageFit.Contain)
          }
          .width('100%')
          .height('100%')
          .justifyContent(FlexAlign.Center)
        }
        .width('100%')
        .aspectRatio(1)
        .backgroundColor($r('app.color.start_window_background'))
        .borderRadius(12)
        .onClick(() => {
          this.showDialog()
        })
      }.visibility(this.isVisibility)
      if (this.isSwiperVisible){
        Swiper(this.swiperController) {
          ForEach(this.imageList, (item: string) => {
            Image(item)
              .width('100%')
              .height('auto')
          }, item => item)
        }
        .cachedCount(2)
        .index(this.currentImageIndex) // 设置当前图片索引
        .autoPlay(false)
        .interval(4000)
        .indicator(true)
        .loop(true)
        .duration(1000)
        .itemSpace(0)
        .curve(Curve.Linear)
        .onClick(()=>{
          this.isSwiperVisible = false; // 关闭 Swiper
          this.isVisibility=Visibility.Visible
        })
      }



    }
    .backgroundColor('#fff8f9fb')
    .width('90%')
    .height('100%')
  }

  addImages = (images: Array<string>) => {
    images.forEach((item: string) => {
      if (!this.imageList.includes(item)) {
        this.imageList.push(item);
      }
    })
    console.log(TAG, `addImages imageList=${JSON.stringify(this.imageList)}`)
  }



  showDialog() {
    AlertDialog.show({
      message: '从相册选择',
      alignment: DialogAlignment.Bottom,
      offset: { dx: 0, dy: -12 },
      primaryButton: {
        value: '取消',
        fontColor: '#0A59F7',
        action: () => {
        }
      },
      secondaryButton: {
        value: '确定',
        fontColor: '#0A59F7',
        action: () => {
          try {
            let photoSelectOptions = new picker.PhotoSelectOptions()
            photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE//文件类型
            photoSelectOptions.maxSelectNumber = 5// 单次选择壁纸数量
            let photoPicker = new picker.PhotoViewPicker()
            photoPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => {
              console.log("photoUris ====="+photoSelectResult.photoUris)
              this.addImages(photoSelectResult.photoUris)
            }).catch((err: string) => {
              console.error(TAG, `'PhotoViewPicker.select failed with err: ${JSON.stringify(err)}`)
            });
          } catch (err) {
            console.error(TAG, `'PhotoViewPicker failed with err: ${JSON.stringify(err)}`)
          }
        }
      }
    })
  }



}


http://www.kler.cn/a/301982.html

相关文章:

  • Tiktok对接和内容发布申请流程
  • 微信小程序navigateTo:fail webview count limit exceed
  • Android Settings 单元测试 | 如何运行单元测试?
  • Win11 终端执行 python xxx.py 没反应
  • C++清除所有输出【DEV-C++】所有编辑器通用 | 算法基础NO.1
  • Java垃圾回收算法
  • Day11笔记-字典基本使用系统功能字典推导式
  • 自定义spring security的安全表达式
  • Numpy中random.seed()函数的使用
  • librdkafka Windows编译
  • 【python因果推断库9】工具变量回归与使用 pymc 验证工具变量2
  • Mac强制删除文件,碰上“拖拽到废纸篓”无法删除时怎么办?
  • 企业供需波动计算数据(2007-2022年)
  • C++设计模式——Iterator迭代器模式
  • 太空技术与商业航天:新时代的探索与经济驱动力
  • 算法提高模板强连通分量tarjan算法
  • [全网首发]怎么让国行版iPhone使用苹果Apple Intelligence
  • 单片机寄存器相关知识及应用(51单片机)
  • 谈谈OpenResty 简介及其容器化实践
  • 大数据-131 - Flink CEP 案例:检测交易活跃用户、超时未交付
  • 被要求撤回Blackwell?一家初创企业称英伟达侵权自家技术,忍无可忍!英伟达和伙伴微软被齐齐告上法庭,赔偿或高达数十亿!
  • Vue的路由守卫与Store
  • 电商API接口安全:构建稳固的数字防线
  • Web开发之Vue.js
  • 数据结构算法——排序算法
  • Xcode报错:No exact matches in reference to static method ‘buildExpression‘