小程序图片适配

1.一般适配:

rpx是WXSS里面的长度单位,会根据屏宽进行自适应。公司的设计图都是750px宽的,因此我适配时,直接替换成对应的rpx单位就行了。比如在设计图上是100px,那么WXSS上就会写成100rpx;在375px屏宽下100rpx会自动换算成50px;

2.精确适配:

通过动态设置image宽高来实现:先在data中用变量表示小图标初始宽高,并绑定到image组件上;再通过wx.getSystemInfo获取屏幕宽度,那么小图标的宽度=原宽*屏宽/设计图宽,长=原长*屏宽/设计图宽,等src载入完毕用this.setData()修改变量。

<image src="01.png" bindload="imageLoad"  
style="width:{{imgwidth}}px; height:{{imgheight }}px;"></image>
Page({
  data: {
    screenWidth: 0,
    imgwidth: 0,
    imgheight: 0
  },
  onLoad: function (options) {
    var _this = this;
    wx.getSystemInfo({
      success: function (res) {
        _this.setData({
          screenWidth: res.windowWidth,
        });
      }
    }); 
  },
  imageLoad: function (e) {
    var _this = this;
    var screenW = this.data.screenWidth;
    var viewWidth = 54 * screenW / 750;
    var viewHeight = viewWidth;
    this.setData({
      imgwidth: viewWidth,
      imgheight: viewHeight
    })
  }
}


猜你喜欢

转载自blog.csdn.net/miss_chen888/article/details/80496615