鸿蒙开发朋友圈九宫格
鸿蒙仿微信朋友圈九宫格,一张是大图,四张是田字形。
一、效果图:
看视频更直观点:
鸿蒙开发教程实战案例源码分享-朋友圈九宫格
二、思路:
自定义NineBoxGrid组件
三、关键代码:
@Component
export struct NineBoxGrid{
photos:PhotoInfo[] = [] // 传进来的数据源
click?:(position:number, imgList:string[]) => void // position为-1时是点击整体;其他是点击对应数据源里的位置
data:NineBoxGridBean[][] = [] // 因为现版本List和Grid有各种问题,所以使用线性布局做,需要数据分组。用数据源处理过后实际使用的数据,
imgList:string[] = [] // 纯图片集合,给预览用的
aboutToAppear(){
let rowNum:number = Math.ceil(this.photos.length / 3)
for(let x = 0; x < rowNum ; x ++){
this.data.push([])
}
this.photos.forEach((value:PhotoInfo, inder:number) =>{
if (value.img){
this.imgList.push(value.img)
}
if(this.photos.length === 4 && inder === 2){
this.data[0].push({position:-1, photos: {}})
this.data[1].push({position:inder, photos: value})
}else{
this.data[Math.floor(inder / 3)].push({position:inder, photos: value})
}
})
let num = 3 - this.data[rowNum - 1].length
for(let x = 0 ; x < num; x ++){
this.data[rowNum - 1].push({position:-1, photos: {}})
}
}
build(){
Column(){
if(this.photos.length === 1){
Row(){
Stack(){
Image(this.photos[0].img).alt($r('app.media.yishi')).width(176).height(243).borderRadius(5)
}
.width(176)
.height(243)
.enabled(this.click ? true : false)
.onClick(() =>{
this.click?.(0,this.photos[0].videoId && this.photos[0].img?[this.photos[0].img!]:this.imgList)
})
Stack(){
}
.layoutWeight(1)
.height(243)
.enabled(this.click ? true : false)
.onClick(() =>{
this.click?.(-1,this.photos[0].videoId && this.photos[0].img?[this.photos[0].img!]:this.imgList)
})
}
.width('100%')
}else{
ForEach(this.data, (itemGroup:NineBoxGridBean[],indexGroup:number) =>{
if(indexGroup > 0){
Divider().width(5).strokeWidth(5).color($r('app.color.color_transparent'))
}
Row(){
ForEach(itemGroup,(item:NineBoxGridBean,index:number) =>{
if(index > 0){
Divider().width(5).strokeWidth(5).color($r('app.color.color_transparent'))
}
Stack(){
if(item.photos?.smallImg && item.photos?.smallImg?.length > 0){
Image(item.photos?.smallImg).width('100%').height('100%').borderRadius(5)
}
}
四、项目demo源码结构图:
有需要完整源码demo学习的私信我,我每天都看私信的。