微信小程序中图片自适应的封装

1、在项目中新建一个util.js 

/**
 * 获取图片的等比例宽高
 */
function imageUtil(e) { 
  var imageSize = {}; 
  var originalWidth = e.detail.width;//图片原始宽 
  var originalHeight = e.detail.height;//图片原始高 
  var originalScale = originalHeight/originalWidth;//图片高宽比 
  console.log('originalWidth: ' + originalWidth) 
  console.log('originalHeight: ' + originalHeight) 
  //获取屏幕宽高 
  wx.getSystemInfo({ 
   success: function (res) { 
    var windowWidth = res.windowWidth; 
    var windowHeight = res.windowHeight; 
    var windowscale = windowHeight/windowWidth;//屏幕高宽比 
    console.log('windowWidth: ' + windowWidth) 
    console.log('windowHeight: ' + windowHeight) 
    if(originalScale < windowscale){//图片高宽比小于屏幕高宽比 
     //图片缩放后的宽为屏幕宽 
      imageSize.imageWidth = windowWidth; 
      imageSize.imageHeight = (windowWidth * originalHeight) / originalWidth; 
    }else{//图片高宽比大于屏幕高宽比 
     //图片缩放后的高为屏幕高 
      imageSize.imageHeight = windowHeight; 
      imageSize.imageWidth = (windowHeight * originalWidth) / originalHeight; 
    } 
      
   } 
  }) 
  console.log('缩放后的宽: ' + imageSize.imageWidth) 
  console.log('缩放后的高: ' + imageSize.imageHeight) 
  return imageSize; 
 } 
 
2、在util.js中使用 将方法暴露出去
module.exports = {
  imageUtil: imageUtil 
}
3、在需要的页面进行绑定动态的宽高,
 <image src="{{list.image}}" style="width: {{imagewidth}}px; height: {{imageheight}}px;" bindload="imageLoad"></image>
4、在js中进行引入
var imageUtil = require('../../utils/util.js');
 /**
   * 图片等比例缩放
   */
   imageLoad: function (e) { 
      var imageSize = imageUtil.imageUtil(e) 
      this.setData({ 
       imagewidth: imageSize.imageWidth, 
       imageheight: imageSize.imageHeight 
      }) 
     },
posted @ 2020-12-03 10:55  小小小~  阅读(139)  评论(0编辑  收藏  举报