18827399046    QQ 1987835510    whxindu            服务范围---网站建设,网上商城,行业门户网站,微网站,手机网站,响应试网站,微信公众号开发
当前位置:首页 > 新闻资讯 > 微信开发

微信小程序单图片的自适应计算

发表日期:2017-04-01 13:42:29编辑:武汉新度网络科技有限公司 标签: 微信小程序,江夏建站,江夏做网站,江夏网站建设,武汉网站建设    

简单的github库

https://github.com/icindy/WxAutoImage


通过image的bindload来计算自适应宽高

微信小程序中image暴漏的函数比较少,但是bindload十分有用。


官方说明: 当图片载入完毕时,发布到 AppService 的事件名,事件对象event.detail = {height:'图片高度px', width:'图片宽度px'}

这里的height:'图片高度px', width:'图片宽度px'都是原始宽高,这就给了我们可以计算的余地

  • 思路

  • 获取图片原始宽高

  • 获取系统屏宽

  • 以原始宽与系统屏宽对比大小,以大者为基准缩放

  • 实现函数


我在主要函数中,加入了少量注释。

/***
 * wxAutoImageCal 计算宽高
 * 
 * 参数 e: iamge load函数的取得的值
 * 返回计算后的图片宽高
 * {
 *  imageWidth: 100px;
 *  imageHeight: 100px;
 * }
 */
function wxAutoImageCal(e){
    console.dir(e);
    //获取图片的原始长宽
    var originalWidth = e.detail.width;
    var originalHeight = e.detail.height;
    var windowWidth = 0,windowHeight = 0;
    var autoWidth = 0,autoHeight = 0;
    var results= {};
    wx.getSystemInfo({
      success: function(res) {
        console.dir(res);
        windowWidth = res.windowWidth;
        windowHeight = res.windowHeight;
        //判断按照那种方式进行缩放
        console.log("windowWidth"+windowWidth);
        if(originalWidth > windowWidth){//在图片width大于手机屏幕width时候
          autoWidth = windowWidth;
          console.log("autoWidth"+autoWidth);
          autoHeight = (autoWidth*originalHeight)/originalWidth;
          console.log("autoHeight"+autoHeight);
          results.imageWidth = autoWidth;
          results.imageheight = autoHeight;
        }else{//否则展示原来的数据
          results.imageWidth = originalWidth;
          results.imageheight = originalHeight;
        }
      }
    })

    return results;

  }


使用

  1. 在image属性绑定函数和动态style

<image bindload="cusImageLoad" src="https://dn-cnode.qbox.me/FjfPMJYFAbyV1-OM-CcCC5Wk2tmY" style="width:{{imageWidth}}px;height:{{imageheight}}px"/>


   2.在load函数中引入计算

//index.js
//获取应用实例
var WxAutoImage = require('../../WxAutoImage/WxAutoImage.js');
var app = getApp()
Page({
  data: {
    
  },
  onLoad: function () {
    console.log('onLoad')
    var that = this
  },
  cusImageLoad: function (e){
    var that = this;
    //这里看你在wxml中绑定的数据格式 单独取出自己绑定即可
    that.setData(WxAutoImage.wxAutoImageCal(e));
  }
})
武汉网站建设|武汉网站制作|武汉网站设计|武汉新度网络有限公司