缩放保持纵横比例缩放图片使多出来的宽和高隐藏。
<view class="box">
<image src="13075_202201191606963564.jpg" style="width: {{imageWidth}}px;height: {{imageHeight}}px;"></image>
</view>
.box{
width: 90px;
height: 120px;
overflow: hidden;
display: flex;
align-items: center;
}
wx.getImageInfo({
src: '',//图片路径
success(res) {
let width = res.width; //图片真实的宽
let height = res.height; //图片真实的高
let str = width / height; //图片的宽高比
let div_width = 90 //假设盒子的宽
let div_height = 120 //假设盒子的高
let top = 0; //图片也可以使用定位得到这个效果,我目前用的是弹性盒子,可以根据需求来改。
let left = 0;
if (str > 1) {
//横版图片---宽比高长--保证短边显示,所以用短边算出要缩小/放大的比例
var ratio = div_height / height //--缩放比例
// 用缩放比例乘以宽高
top = (ratio * height - div_height) / 2;
left = (ratio * width - div_width) / 2;
that.setData({
imageWidth: ratio * width,
imageHeight: ratio * height,
imageLeft: left,
imageTop: top
})
} else {
//竖版图片---高比宽长-----宽是短边
var ratio = div_width / width //--缩放比例
// 用缩放比例乘以宽高
top = (ratio * height - div_height) / 2;
left = (ratio * width - div_width) / 2;
that.setData({
imageWidth: ratio * width,
imageHeight: ratio * height,
imageLeft: left,
imageTop: top,
})
}
}
})