The origin of

Recently, I have been making requirement A, in which A small function point is described as follows: return A picture from the configuration end, the expected width is unchanged (750), and the height is self-adaptive according to the picture.

I thought of

< span style="width:100%; > <image src="{{src}}"></image> </view>Copy the code

The first thing I thought was: Set width of the content area to 100% to automatically fill the screen width, and the height will be adaptive.Actual effect: Image occupies the screen width x 0

The solution

Core: How to get the height of the picture

The primary plan

Key points:Obtain the corresponding image information after the image is loaded.

After checking the applets development documentation, we found that there is a callback that provides a successful load, as follows: The Demo is as follows:

// wxml
<view style="width:100%;" >
  <image src="https://sf3-ttcdn-tos.pstatp.com/img/mosaic-legacy/3796/2975850990~300x300.image" bindload="loadSuccess" style="width:{{imageWidth}}px; height:{{imageHeight}}px"></image>
</view>

//js
Page({
  data: {
    imageHeight: 0,
    imageWidth: 0
  },
  loadSuccess(e){
    const { detail: {width, height} } = e
    this.setData({
      imageWidth: width,
      imageHeight:height
    })
  }
})
Copy the code

Take a look at the results first: Consider this question:Let’s say I have 100 images that all need to be adaptive, so is there a lot of tedious setData(), which will also cause performance problems?

Advanced solutions

After being reminded by my friend, I found that the small program image also has an attribute called mode, which can set the cropping & zooming and other forms of pictures.The mode attribute can be selected as follows:Without further ado, let’s see how this works in practice:

< p style=" margin-top: 1em; margin-bottom: 1em; > <image src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/ba1f75f0d29c40759b43ef910dacb4e7~tplv-k3u1fbpfcp-watermark.image" Mode ="widthFix"></image> </view> > <image src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/ba1f75f0d29c40759b43ef910dacb4e7~tplv-k3u1fbpfcp-watermark.image"  mode="widthFix"></image> </view>Copy the code

Take a look at this 750×110:Take a look at the renderings of 750×480:SRC = “SRC”; SRC = “SRC”; SRC = “SRC”; SRC = “SRC”

The last

The main purpose of this attribute is to make the image adaptive and, in other words, to ensure that the image is not distorted.