在項目中由于需要上傳不同的輪播圖片,但是圖片可能尺寸不一樣,導(dǎo)致會顯示圖片變形,很難看,所以最后弄了一個圖片自適應(yīng)的組件,可以解決這個問題.
實現(xiàn)原理
其實實現(xiàn)就是獲取到每張圖片的寬高,然后根據(jù)每張圖片的,結(jié)合當(dāng)前屏幕的寬度,計算出需要的最大高度,因為屏幕寬度是不變的,根據(jù)這個高度設(shè)置swiper容器的高度,再給每張圖片加上mode='widthFix'屬性,這樣圖片就會自適應(yīng)顯示,不會變形.
但是缺點是我獲取到的圖片寬高是通過微信小程序API wx.getImageInfo,這個接口是要先把圖片下載下來,所以要求圖片是https,還要小程序后臺綁定對應(yīng)downLoad域名,測試在工具上勾選不驗證域名查看效果,還有圖片大會稍微有點慢,不知道有沒有其他人有不同實現(xiàn)方法.
效果圖
兩張圖片高度不一樣
實現(xiàn)過程
1.組件
Component({
/**
* 組件的屬性列表
*/
properties: {
listimg: {//傳進來的圖片數(shù)組
type: null
},
},
/**
* 組件的初始數(shù)據(jù)
*/
data: {
configimg: [],
indicatorDots: true,
autoplay: true,
interval: 3000,
duration: 1000,
swiperCurrent: 0
},
ready: function() {
this.initData();
},
/**
* 組件的方法列表
*/
methods: {
//格式化數(shù)組
initData: function() {
if (!this.data.listimg && this.data.listimg.length == 0){
console.log("沒有圖片")
return;
}
let list = this.data.listimg;
let newList = [];
for (let i = 0; i < list.length; i++) {
let h = {};
h.showImg = list[i];
newList.push(h);
}
this.getDownLoadimg(newList);
},
//獲取圖片真實寬高
getDownLoadimg: function(list) {
let that = this;
let f = 0;
for (let h = 0; h < list.length; h++) {
wx.getImageInfo({
src: list[h].showImg,
success: function(res) {
list[h].width = res.width;
list[h].height = res.height;
},
fail: function(err) {
console.log("錯誤")
console.log(err)
},
complete: function(res) {
f++
if (f == list.length) {
console.log('執(zhí)行完畢');
that.getImgMax(list)
} else {
console.log("繼續(xù)");
}
}
})
}
},
//計算高度比求最大高度值
getImgMax: function(list) {
let heightArr = [];
for (let g = 0; g < list.length; g++) {
//獲取圖片真實寬度
var imgwidth = list[g].width,
imgheight = list[g].height,
//寬高比
ratio = imgwidth / imgheight;
//計算的高度值
var viewHeight = 750 / ratio;
var imgheight = viewHeight
heightArr.push(imgheight)
list[g].imgheight = imgheight;
}
for (let t = 0; t < list.length; t++) {
var maxN = this.checkMax(heightArr)
list[t].maxHeight = maxN;
}
console.log(list)
this.setData({
configimg: list
})
},
//判斷最大值
checkMax: function(heightArr) {
let maxN = Math.max.apply(null, heightArr);
return maxN;
},
}
})