小程序实现图片垂直居中,水平居中并且自适应宽高

效果如下图:

小程序实现图片垂直居中,水平居中并且自适应宽高小程序实现图片垂直居中,水平居中并且自适应宽高

html部分:

<view class='imgCon'>

<image src='{{goods.goodsPhotoUrl}}' bindload='imgLoad' style='width:{{width}}rpx;height:{{height}}rpx;' ></image><!-- 改动态对应的商品图 -->

</view>

css部分:(css这样设置虽然可以垂直居中,水平居中,但是图片是变形的,所以需要用到js来修改图片宽高)

.imgCon{

width: 160rpx;

height: 160rpx;

display: inline-block;

vertical-align: top;

margin-right: 20rpx;

overflow: hidden;

position: relative;

}

.imgCon image{

width: 160rpx;

height: 160rpx;

position: absolute;

top: 50%;

left: 50%;

transform: translate(-50%,-50%);

}

js部分:

//图片宽高处理

imgLoad:function(e){

var that = this;

console.info(e.detail);

var imgwidth = e.detail.width;

var imgheight = e.detail.height;

var width,height;

var ratio;

if(imgwidth>imgheight){

ratio = imgwidth / 160;

width = 160;

height = imgheight / ratio;

}else{

ratio = imgheight / 160;

height = 160;

width = imgwidth / ratio;

}

console.info("计算后的宽高", width, height);

that.setData({

width:width,

height:height

})

}