微信小程序轮播图片自适应显示组件

在项目中由于需要上传不同的轮播图片,但是图片可能尺寸不一样,导致会显示图片变形,很难看,所以最后弄了一个图片自适应的组件,可以解决这个问题.

实现原理

其实实现就是获取到每张图片的宽高,然后根据每张图片的,结合当前屏幕的宽度,计算出需要的最大高度,因为屏幕宽度是不变的,根据这个高度设置swiper容器的高度,再给每张图片加上mode='widthFix'属性,这样图片就会自适应显示,不会变形.

但是缺点是我获取到的图片宽高是通过微信小程序API wx.getImageInfo,这个接口是要先把图片下载下来,所以要求图片是https,还要小程序后台绑定对应downLoad域名,测试在工具上勾选不验证域名查看效果,还有图片大会稍微有点慢,不知道有没有其他人有不同实现方法.

效果图

5323615-44c35cc945c3444c.png
两张图片高度不一样

实现过程

1.组件

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    listimg: {//传进来的图片数组
      type: null
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    configimg: [],
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    swiperCurrent: 0
  },
  ready: function() {
    this.initData();
  },
  /**
   * 组件的方法列表
   */
  methods: {
    //格式化数组
    initData: function() {
      if (!this.data.listimg && this.data.listimg.length == 0){
        console.log("没有图片")
         return;
      }
      let list = this.data.listimg;
      let newList = [];
      for (let i = 0; i < list.length; i++) {
        let h = {};
        h.showImg = list[i];
        newList.push(h);
      }
      this.getDownLoadimg(newList);
    },

    //获取图片真实宽高
    getDownLoadimg: function(list) {
      let that = this;
      let f = 0;
      for (let h = 0; h < list.length; h++) {
        wx.getImageInfo({
          src: list[h].showImg,
          success: function(res) {
            list[h].width = res.width;
            list[h].height = res.height;
          },
          fail: function(err) {
            console.log("错误")
            console.log(err)
          },
          complete: function(res) {
            f++
            if (f == list.length) {
              console.log('执行完毕');
              that.getImgMax(list)
            } else {
              console.log("继续");
            }
          }
        })
      }
    },

    //计算高度比求最大高度值
    getImgMax: function(list) {
      let heightArr = [];
      for (let g = 0; g < list.length; g++) {
        //获取图片真实宽度  
        var imgwidth = list[g].width,
          imgheight = list[g].height,
          //宽高比  
          ratio = imgwidth / imgheight;
        //计算的高度值  
        var viewHeight = 750 / ratio;
        var imgheight = viewHeight
        heightArr.push(imgheight)
        list[g].imgheight = imgheight;
      }
      for (let t = 0; t < list.length; t++) {
        var maxN = this.checkMax(heightArr)
        list[t].maxHeight = maxN;
      }
      console.log(list)
      this.setData({
        configimg: list
      })
    },

    //判断最大值
    checkMax: function(heightArr) {
      let maxN = Math.max.apply(null, heightArr);
      return maxN;
    },
  }
})

详细请demo地址

猜你喜欢

转载自blog.csdn.net/weixin_34279184/article/details/87212461