HarmonyOS NEXT仓颉开发语言实战案例:图片预览器
上文分享了如何使用仓颉语言实现动态广场,动态广场中有很多图片,本文一下如何使用仓颉语言实现一个图片放大预览器:
看到这个效果,我首先想到的实现方案是弹窗,弹窗的弹出和消失效果为我们节省了很多工作,这里使用的是CustomDialogController。
我们首先实现弹窗内容组件,图片预览可能会有不同数量的图片,我们要做好适配,还要实现翻页效果,所以使用swiper容器最为合适,具体代码如下,大家要注意接收参数的定义和弹窗点击关闭代码的写法:
package ohos_app_cangjie_entry import ohos.base.* import ohos.component.* import ohos.state_manage.* import ohos.state_macro_manage.* import cj_res_entry.app import std.collection.ArrayList @CustomDialog public class imgdialog { var controller: Option<CustomDialogController> = Option.None @Prop var imgList:ArrayList<CJResource> func build() { Swiper(){ ForEach(imgList, itemGeneratorFunc: {img:CJResource,index:Int64 => Image(img) .width(100.percent) .height(100.percent) .objectFit(ImageFit.Contain) }) } .width(100.percent) .height(100.percent) .backgroundColor(Color(0, 0, 0, alpha: 0.6)) .onClick({e => controller.getOrThrow().close() }) } }
以上的代码里,大家还是需要注意仓颉语言循环渲染Foreach的写法,它和ArkTS是稍有不同的,主要的区别是增加了itemGeneratorFunc结构体。另外,在Swiper组件的点击事件中,我写了controller.getOrThrow().close()来关闭弹窗,getOrThrow()这个方法的作用大家看名字应该可以猜到,它的作用是取值或者抛出一个异常,这样能够避免很多代码运行时的错误。
接下来的工作就是初始化一个弹窗对象,弹窗组件默认是不能占满全屏的,这时候只需要设置customStyle值为true就可以了,autoCancel参数的作用是支持弹窗自动消息,具体代码如下:
@State var imglist:ArrayList<CJResource> = ArrayList<CJResource>() var dialogController: CustomDialogController = CustomDialogController(CustomDialogControllerOptions( builder: imgdialog(imgList:imglist), customStyle:true, autoCancel:true ))
最后在点击图片的时候打开弹窗:
imglist = item.getImages() dialogController.open()
今天的内容分享完啦,感谢大家阅读。##HarmonyOS语言##仓颉##休闲娱乐#
#harmonyos#