找回密码
 立即注册
首页 业界区 安全 HarmonyOS NEXT仓颉开发语言实战案例:图片预览器 ...

HarmonyOS NEXT仓颉开发语言实战案例:图片预览器

褥师此 2025-6-28 15:32:35
上文分享了如何使用仓颉语言实现动态广场,动态广场中有很多图片,本文一下如何使用仓颉语言实现一个图片放大预览器:
1.png

看到这个效果,我首先想到的实现方案是弹窗,弹窗的弹出和消失效果为我们节省了很多工作,这里使用的是CustomDialogController。
我们首先实现弹窗内容组件,图片预览可能会有不同数量的图片,我们要做好适配,还要实现翻页效果,所以使用swiper容器最为合适,具体代码如下,大家要注意接收参数的定义和弹窗点击关闭代码的写法:
  1. package ohos_app_cangjie_entry
  2. import ohos.base.*
  3. import ohos.component.*
  4. import ohos.state_manage.*
  5. import ohos.state_macro_manage.*
  6. import cj_res_entry.app
  7. import std.collection.ArrayList
  8. @CustomDialog
  9. public  class imgdialog {
  10.     var controller: Option<CustomDialogController> = Option.None
  11.     @Prop var imgList:ArrayList<CJResource>
  12.     func build() {
  13.         Swiper(){
  14.             ForEach(imgList, itemGeneratorFunc: {img:CJResource,index:Int64 =>
  15.                         Image(img)
  16.                         .width(100.percent)
  17.                         .height(100.percent)
  18.                         .objectFit(ImageFit.Contain)
  19.                         })
  20.         }
  21.         .width(100.percent)
  22.         .height(100.percent)
  23.         .backgroundColor(Color(0, 0, 0, alpha: 0.6))
  24.         .onClick({e =>
  25.             controller.getOrThrow().close()
  26.                 })
  27.     }
  28. }
复制代码
回到动态广场,这里要先初始化弹窗对象,并且传入图片列表:
  1. @State var imglist:ArrayList<CJResource> = ArrayList<CJResource>()
  2. var dialogController: CustomDialogController = CustomDialogController(CustomDialogControllerOptions(
  3.     builder: imgdialog(imgList:imglist),
  4.     customStyle:true,
  5.     autoCancel:true
  6. ))
复制代码
在弹窗的配置参数中,设置customStyle为true可以使弹窗全屏展示。最后在点击图片的时候打开弹窗:
  1. imglist = item.getImages()dialogController.open()
复制代码
今天的内容分享完啦,感谢大家阅读。##HarmonyOS语言##仓颉##休闲娱乐#

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册