鸿蒙开发朋友圈九宫格

鸿蒙开发朋友圈九宫格

鸿蒙仿微信朋友圈九宫格,一张是大图,四张是田字形。

一、效果图:

在这里插入图片描述

看视频更直观点:

鸿蒙开发教程实战案例源码分享-朋友圈九宫格

二、思路:

自定义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学习的私信我,我每天都看私信的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

893151960

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值