Applet image width height adaption

1, Understanding image components

Because the image has a default fixed width and height, it is not easy for us to adapt the image. Let's solve it together

Two. Method

(1) . using mode: widthFix

widthFix: the width is the same, the height changes automatically, and the width height ratio of the original image is the same.
First, we set the image mode to widthFix, and then add a fixed rpx width to the image, such as 730rpx.
In this way, the picture can also be adaptive.. Because the rpx of the applet itself is an adaptive display unit

(2) . use the bindload binding function to dynamically adapt.
We can bind a function to image. This function, like the bindload description above, can get the width and height of the original image.
Then calculate their aspect ratio.. Then set a width size (rpx), and finally dynamically set the width and height of image through style. The code is as follows:

1. Write the page structure index.wxml:

  1. <span style="font-family:'Comic Sans MS';font-size:18px;color:#333333;"><image src="../uploads/2.jpg" bindload="imageLoad"  
  2. style="width:{{imgwidth}}rpx; height:{{imgheight }}rpx;"></image></span>  
2. Set data index.js
  1. <span style="font-family:'Comic Sans MS';font-size:18px;color:#333333;">//Get application instance
  2. var app = getApp()  
  3. Page({  
  4.     data: {  
  5.         screenWidth: 0,  
  6.         screenHeight:0,  
  7.         imgwidth:0,  
  8.         imgheight:0,  
  9.     },  
  10.     onLoad: function() {  
  11.         var _this = this;  
  12.         wx.getSystemInfo({  
  13.             success: function(res) {  
  14.                 _this.setData({  
  15.                     screenHeight: res.windowHeight,  
  16.                     screenWidth: res.windowWidth,  
  17.                 });  
  18.             }  
  19.         });  
  21.     },  
  22.     imageLoad: function(e) {  
  23.         var _this=this;  
  24.         var $width=e.detail.width,    //Get the true width of the picture
  25.             $height=e.detail.height,  
  26.             ratio=$width/$height;   //True aspect ratio of picture
  27.         var viewWidth=500,           //Set the picture display width
  28.             viewHeight=500/ratio;    //Calculated height value
  29.         this.setData({  
  30.             imgwidth:viewWidth,  
  31.             imgheight:viewHeight  
  32.         })  
  33.     }  
  34. })</span>  

Added by lanas on Tue, 31 Mar 2020 21:47:14 +0300