likes
comments
collection
share

微信小程序获取图片的原始尺寸并且重新设置宽高

作者站长头像
站长
· 阅读数 19

最近在开发一个功能,接口返回的图片如果高度大于当前手机屏幕的高度,就让图片可以滚动,否则就让图片撑满整个屏幕,并且禁止滚动。方法是wx.getImageInfo,微信官方文档

获取一张图片宽高的代码:

        wx.getImageInfo({
          src: this.data.info.imgUrl,
          complete: (res) => {
            // 原图的宽度
            let imgWidth = res.width;
            // 原图的高度
            let imgHeight = res.height;
            // 设备的宽度
            let screenWidth = wx.getSystemInfoSync().windowWidth;
            // 设备的高度
            let screenHeight = wx.getSystemInfoSync().windowHeight;
            // 750 2000
            // 图片的宽度除以屏幕的宽度
            let ratio2 = imgWidth / screenWidth;
            // 获取被渲染后的图片高度
            let saleHight = (imgHeight / ratio2).toFixed(2);
            if (saleHight >= screenHeight) {
              this.setData({
                ['info.width']: screenWidth + 'px',
                ['info.height']: saleHight + 'px',
                ['info.mode']: 'aspectFit',
              });
            } else {
              this.setData({
                ['info.width']: '100%',
                ['info.height']: '100%',
                ['info.mode']: 'aspectFill',
              });
            }
          }
        })

获取循环里面图片宽高的代码:

          this.data.list.forEach((item, index) => {
            wx.getImageInfo({
              src: item.info.imgUrl,
              complete: (res) => {
                // 原图的宽度
                let imgWidth = res.width;
                // 原图的高度
                let imgHeight = res.height;
                let screenWidth = wx.getSystemInfoSync().windowWidth;
                let screenHeight = wx.getSystemInfoSync().windowHeight;    
                // 750 2000
                // 图片的宽度除以屏幕的宽度
                let ratio2 = imgWidth / screenWidth;
                // 获取被渲染后的图片高度
                let saleHight = (imgHeight / ratio2).toFixed(2);
                if(saleHight >= screenHeight) {
                  this.setData({
                    [`list[${index}]info.width`]: screenWidth + 'px',
                    [`list[${index}]info.height`]: saleHight + 'px',
                    [`list[${index}]info.mode`]: 'aspectFit',
                  });
                } else {
                  this.setData({
                    [`list[${index}]info.width`]: '100%',
                    [`list[${index}]info.height`]: '100%',
                    [`list[${index}]info.mode`]: 'aspectFill',
                  });
                }
              }
            })
          })

实现了我想要的功能,需要注意wx.getImageInfo是异步的。