欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  互联网

【微信小程序】根据屏幕尺寸去调整图片尺寸宽高比

程序员文章站 2022-06-19 15:42:56
1.获取图片的原始宽高,并获取到图片原始宽高的宽高比let src = "图片地址"wx.getImageInfo({ src, success: function(res){ let originalWidth = res.width; let originalHeight = res.height; let originalScale = parseInt(originalHeight/originalWidth);//图片高宽比...

1.获取图片的原始宽高,并获取到图片原始宽高的宽高比

let src = "图片地址"
wx.getImageInfo({
    src,
    success: function(res){
        let originalWidth = res.width;
        let originalHeight = res.height;
        let originalScale = parseInt(originalHeight/originalWidth);//图片高宽比   
    }
})

2.获取屏幕的宽高,并获取到屏幕宽高的宽高比


        wx.getSystemInfo({
            success: function (res) {
              let windowWidth = res.windowWidth - 36 ;
              let windowHeight = res.windowHeight;
              let windowscale = parseInt(windowHeight/windowWidth);//屏幕高宽比
            }
        })

3.计算图片尺寸

if(originalScale < windowscale){//图片高宽比小于屏幕高宽比
    //图片缩放后的宽为屏幕宽
    imageSize.imageWidth = parseInt(windowWidth);
    imageSize.imageHeight = parseInt((windowWidth * originalHeight) / originalWidth);
}else{//图片高宽比大于屏幕高宽比
    //图片缩放后的高为屏幕高
    imageSize.imageHeight = parseInt(windowHeight);
    imageSize.imageWidth = parseInt((windowHeight * originalWidth) / originalHeight);
}

4.整合代码,方便调用 新建一个util.js

function imageUtil(src,callback) {
  let imageSize = {};
  wx.getImageInfo({
    src,
    success: function(res){
      console.log(res,"1111111111111111111111")
      let originalWidth = res.width;
      let originalHeight = res.height;
      let originalScale = parseInt(originalHeight/originalWidth);//图片高宽比
      console.log('originalWidth: ' + originalWidth)
      console.log('originalHeight: ' + originalHeight)
      console.log(app.globalData)

      wx.getSystemInfo({
        success: function (res) {
          let windowWidth = res.windowWidth - 36 ;
          let windowHeight = res.windowHeight;
          let windowscale = parseInt(windowHeight/windowWidth);//屏幕高宽比
          console.log('windowWidth: ' + windowWidth)
          console.log('windowHeight: ' + windowHeight)
          if(originalScale < windowscale){//图片高宽比小于屏幕高宽比
            //图片缩放后的宽为屏幕宽
            imageSize.imageWidth = parseInt(windowWidth);
            imageSize.imageHeight = parseInt((windowWidth * originalHeight) / originalWidth);
          }else{//图片高宽比大于屏幕高宽比
            //图片缩放后的高为屏幕高
            imageSize.imageHeight = parseInt(windowHeight);
            imageSize.imageWidth = parseInt((windowHeight * originalWidth) / originalHeight);
          }
        },
      })
      console.log('缩放后的宽: ' + imageSize.imageWidth)
      console.log('缩放后的高: ' + imageSize.imageHeight)
      return callback(imageSize);
    }
  })

//抛出
module.exports = {
  imageUtil,
}

本文地址:https://blog.csdn.net/qq_37949737/article/details/109247673