微信小程序(八)实战——加载图片images

1.加载本地图片

本地路径:/pages/images/1.png

<image class="widget_arrow" src="/pages/images/1.png" mode="aspectFill"></image>

在wxss中设置图片样式

.widget_arrow{
    width:25px; 
    height:25px; 
}

2.加载网络图片

网络图片地址:http://img1.3lian.com/2015/w7/85/d/101.jpg

<image class="widget_arrow2" src="http://img1.3lian.com/2015/w7/85/d/101.jpg" mode="aspectFill"></image>
在wxss中设置图片样式

.widget_arrow2{
    width:155px; 
    height:155px; 
}
结果:

3.点击选择-加载图片

3-1:我们定义的全局变量,也就是data中的url,已经有值了,现在只需要在页面中显示即可。
//点击此按钮调用选择图片的方法,成功后将图片显示在image标签上
<button bindtap="bindViewTap" type="submit">点击我显示图片</button>
<image src="{{avatarUrl}}" class="widget_arrow3"></image>

3-2:wx.chooseImage({})此方法是用来选择图片的方法

bindViewTap: function () {
    var that = this;
    wx.chooseImage({
      // 设置最多可以选择的图片张数,默认9,如果我们设置了多张,那么接收时//就不在是单个变量了,
      count: 1,
      sizeType: ['original', 'compressed'], // original 原图,compressed 压缩图,默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有
      success: function (res) {
        // 获取成功,将获取到的地址赋值给临时变量
        var tempFilePaths = res.tempFilePaths;
        that.setData({
          //将临时变量赋值给已经在data中定义好的变量
          avatarUrl: tempFilePaths
        })
      },
      fail: function (res) {
        // fail
    },
      complete: function (res) {
        // complete
    }
    })
  },

3-3:点击后选择,再显示

1


2

4.加载多张图片

4-1:首先在data中定义好数据源:

data: {
    avatarUrl: null,
    pictures: 
    ['/pages/images/1.png',
        '/pages/images/2.png',
        '/pages/images/3.png',
    ]
  },

4-2:然后创建方法previewImage,实现图片预览:

previewImage: function (e) {
    var that = this,
      //获取当前图片的下表
      index = e.currentTarget.dataset.index,
      //数据源
      pictures = this.data.pictures;
    wx.previewImage({
      //当前显示下表
      current: pictures[index],
      //数据源
      urls: pictures
    })
  },

4-3:然后再页面中边遍历数据,显示:

<view>
 <image wx:for="{{pictures}}" wx:key="unique"src="{{item}}" data-index="{{index}}" bindtap="previewImage" class="widget_arrow3"></image>
</view>

4-4:可以在wxss中设置样式

.widget_arrow3{
    width:55px; 
    height:55px; 
}

猜你喜欢

转载自blog.csdn.net/qq_38191191/article/details/80916346