Home  >  Article  >  WeChat Applet  >  WeChat applet implements image adaptive width

WeChat applet implements image adaptive width

小云云
小云云Original
2018-03-17 13:16:566983browse

This article mainly shares with you the WeChat applet to implement image adaptive width. I hope it can help you. First, let's take a look at the image component.

1. Understand the image component

##Since image has a default fixed width and Height, this will make it difficult for us to adapt the image. Let’s solve it together

2. Method

(1).Use mode: widthFix

widthFix: The width remains unchanged and the height changes automatically, keeping the aspect ratio of the original image unchanged. First we set the image mode to widthFix, and then add a fixed rpx width to the image, such as: 730rpx.
This way the picture can also be adapted. . Because the rpx of the mini program itself is an adaptive display unit


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

1.. Write the page structure index.wxml:

<image src="../uploads/2.jpg" bindload="imageLoad"
style="width:{{imgwidth}}rpx; height:{{imgheight }}rpx;"></image>

2.Set data index.js

//获取应用实例 
var app = getApp()
Page({
	data: {
		screenWidth: 0,
		screenHeight:0,
		imgwidth:0,
		imgheight:0,
	},
	onLoad: function() {
		var _this = this;
		wx.getSystemInfo({
			success: function(res) {
				_this.setData({
					screenHeight: res.windowHeight,
					screenWidth: res.windowWidth,
				});
			}
		});

	},
  	imageLoad: function(e) {
  		var _this=this;
		var $width=e.detail.width,    //获取图片真实宽度
		    $height=e.detail.height,
		    ratio=$width/$height;   //图片的真实宽高比例
		var viewWidth=500,           //设置图片显示宽度,
            viewHeight=500/ratio;    //计算的高度值   
		this.setData({
			imgwidth:viewWidth,
		    imgheight:viewHeight
		})
  	}
})

##Related recommendations:

Summary of 10 image library examples

The above is the detailed content of WeChat applet implements image adaptive width. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn