小程序里一个实用的多功能相片选择器
发布于 4 年前 作者 baijie 5021 次浏览 来自 分享

功能特色

1.拍照拾取——拍照取景更快一步

2.微信聊天记录中选取——有了这个,不用先保存本地,再浏览上传了

3.相册中选择——取相片经典内味儿​

界面演示

布局代码



<view class="body">

  

  <camera device-position="back" flash="off" binderror="error">camera>

<view class=“item footer” style=“margin-bottom: {{marginBottom}}px;”> <view bindtap=“choose”>手机相册view> <image src="…/…/…/images/photo.png" class=“photo” bindtap=“takePhoto” /> <view bindtap=“chooseMessageFile”>微信图片view> view> view>

其中唤起系统拍照界面,在页面再在画一个绑定一个takePhoto事件,就可以回调取出刚刚所拍的相片。

JS代码


Page({

  takePhoto() {

    const ctx = wx.createCameraContext()

    ctx.takePhoto({

      quality: 'high',

      success: res => {

        const file = res.tempImagePath

        this.navi(file)

      }

    })

  },

  error(e) {

    console.log(e.detail)

  },

  chooseMessageFile() {

    wx.chooseMessageFile({

      count: 1,

      type: 'image',

      success: res => {

        // tempFilePath可以作为img标签的src属性显示图片

        const tempFilePaths = res.tempFiles

        const file = tempFilePaths[0].path

        this.navi(file)

      }

    })

  },

  choose() {

    wx.chooseImage({

      count: 1,

      sourceType: ['album'],

      success: res => {

        let file = res.tempFilePaths[0]

        this.setData({

          file: file

        })

        this.navi(file)

      }

    })

  },

})

除了刚刚提到的takePhoto方法,另外2个方法chooseMessageFile对应的是从好友聊天记录里的图片,而choose方法,就是从传统的相册中取出相片

wxss样式表


page {

  background: #111;

  height: 100%;

}

.item {

  display: flex;

  flex-direction: row;

  justify-content: space-between;

  align-items: center;

  padding: 10px;

}

.photo {

  width: 60px;

  height: 60px;

}

.footer view {

  color: white;

}

.body {

  display: flex;

  flex-direction: column;

  justify-content: space-between;

  height: 100%;

}

.body camera {

  flex: 1;

  width: 100%;

}

body这个类样式就是flex布局,目的是配合cameraflex: 1使用得camera标签能够自适应高度到最大高度,而item这个类样式则是让底部操作区上的相册选择、拍照、微信选择三个按钮均匀横排。

在线体验

关注我

1 回复
回到顶部