小程序中的图片宽度固定 高度按比例自适应

961 阅读1分钟

问题:

按照UI的设计稿完成后,产品看到实现效果忙不迭的跑来了,说我配的图,都被截断了,这不是他想要的啊。然后忙不迭的又跑去找UI了。UI说,我的锅,这就改设计图,结果:开发就得无条件的改改改!!

调研:

web端的同事告诉我,width:100%,height不设,图片就会自动撑起来拉,so easy。但是。。。,easy出来的并没有效果!!然后去查了文档,image标签给的定义是这样的:

一定要注意这个里面的<注1>,因为如果不设置高度,会有一个默认的高度(我测试的设备是width:375px,会莫名奇妙的有个240px的默认高度)

定义中有个函数叫bindload,这个函数会返回具体的图片高度,只要加载完成后,重新设置下这个style,就可以达到效果了。

实现

下面是具体的实现代码,仅供参考:

    let width = event.detail.width
    let height = event.detail.height

    let windowWidth = wx.getSystemInfoSync().windowWidth
    let imageWith = windowWidth - 30
    let percent = (height / width) * 100 * (windowWidth - 30) / windowWidth
    let imageHeight = height * imageWith / width

    let detailIndex = event.currentTarget.dataset.key

    let list = this.data.detailImageLoadList || []
    let imageValue = {
      loaded: true,
      width: imageWith,
      height: imageHeight
    }
    list[detailIndex] = imageValue
    this.setData({
      detailImageLoadList: list
    })

在wxml中,设置style:

   <image style="{{detailImageLoadList[index].width ? detailImageLoadList[index].width : 0}}px; height:{{detailImageLoadList[index].height ? detailImageLoadList[index].height : 0}}px"  src="" mode="aspectFill" bindload="detailPicLoad" data-key="{{index}}"/>

OK,Done!

PS: 上面设置style的长语句,看着非常丑,可有优化的方法?(来自一个初学web的小伙伴)