上文分享了如何使用倉(cāng)頡語(yǔ)言實(shí)現(xiàn)動(dòng)態(tài)廣場(chǎng),動(dòng)態(tài)廣場(chǎng)中有很多圖片,本文一下如何使用倉(cāng)頡語(yǔ)言實(shí)現(xiàn)一個(gè)圖片放大預(yù)覽器:

看到這個(gè)效果,我首先想到的實(shí)現(xiàn)方案是彈窗,彈窗的彈出和消失效果為我們節(jié)省了很多工作,這里使用的是CustomDialogController。
我們首先實(shí)現(xiàn)彈窗內(nèi)容組件,圖片預(yù)覽可能會(huì)有不同數(shù)量的圖片,我們要做好適配,還要實(shí)現(xiàn)翻頁(yè)效果,所以使用swiper容器最為合適,具體代碼如下,大家要注意接收參數(shù)的定義和彈窗點(diǎn)擊關(guān)閉代碼的寫法:
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()
})
}
}
以上的代碼里,大家還是需要注意倉(cāng)頡語(yǔ)言循環(huán)渲染Foreach的寫法,它和ArkTS是稍有不同的,主要的區(qū)別是增加了itemGeneratorFunc結(jié)構(gòu)體。另外,在Swiper組件的點(diǎn)擊事件中,我寫了controller.getOrThrow().close()來(lái)關(guān)閉彈窗,getOrThrow()這個(gè)方法的作用大家看名字應(yīng)該可以猜到,它的作用是取值或者拋出一個(gè)異常,這樣能夠避免很多代碼運(yùn)行時(shí)的錯(cuò)誤。
接下來(lái)的工作就是初始化一個(gè)彈窗對(duì)象,彈窗組件默認(rèn)是不能占滿全屏的,這時(shí)候只需要設(shè)置customStyle值為true就可以了,autoCancel參數(shù)的作用是支持彈窗自動(dòng)消息,具體代碼如下:
@State var imglist:ArrayList<CJResource> = ArrayList<CJResource>()
var dialogController: CustomDialogController = CustomDialogController(CustomDialogControllerOptions(
builder: imgdialog(imgList:imglist),
customStyle:true,
autoCancel:true
))
在彈窗的配置參數(shù)中,設(shè)置customStyle為true可以使彈窗全屏展示。最后在點(diǎn)擊圖片的時(shí)候打開(kāi)彈窗:
imglist = item.getImages()dialogController.open()
今天的內(nèi)容分享完啦,感謝大家閱讀。##HarmonyOS語(yǔ)言##倉(cāng)頡##休閑娛樂(lè)#