今天一位粉丝问了一个问题,关于小程序本地相册选择图片或相机拍照底部弹框功能,小程序根据文档来写,为什么没有底部弹框,点击按钮就直接打开了手机相册了。看了一下不是他代码的原因,也不是什么bug,而是只写了部分功能。今天把这两个功能连起来说一说。
老规矩,放上小程序官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/wx.chooseImage.html
官网里面的代码,使用chooseImage
即可,count
表示最多可以选择的图片张数, sizeType
表示所选的图片的尺寸sourceType
表示选择图片的来源,详情可以仔细阅读一下文档。
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success(res) {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths = res.tempFilePaths
}
})
有很多功能设计的时候是这样的,点击按钮之后会从手机的底部弹出来一个询问按钮,询问是从手机里选择一张照片,还是调用摄像功能拍摄照片,这个时候其实只要多调用一下这个函数showActionSheet
就可以了。
效果如下:点击按钮,选择图片进行替换,或者拍到一张照片,进行更换。
代码:
wxml:
<view class="container">
<view>
<button class="btn" bindtap="chooseimage">点击更换图片</button>
</view>
<view>
<image src="{{img}}" catchTap="chooseImageTap" mode="aspectFit" class="img" />
</view>
</view>
wxss:
.btn {
margin: 140rpx;
}
.img {
width: 100%;
height: 480rpx;
}
js
Page({
data: {
img: '../../images/1.jpg'
},
onLoad: function() {},
chooseWxImage: function(type) {
var that = this;
wx.chooseImage({
sizeType: ['original', 'compressed'],
sourceType: [type],
success: function(res) {
console.log(res);
that.setData({
// tempFilePath可以作为img标签的src属性显示图片
img: res.tempFilePaths[0],
})
}
})
},
chooseimage: function() {
var that = this;
wx.showActionSheet({
itemList: ['从相册中选择', '拍照'],
itemColor: "#a3a2a2",
success: function(res) {
if (!res.cancel) {
if (res.tapIndex == 0) {
that.chooseWxImage('album')
} else if (res.tapIndex == 1) {
that.chooseWxImage('camera')
}
}
}
})
},
})
原文作者:祈澈姑娘 技术博客:https://www.jianshu.com/u/05f416aefbe1
90后前端妹子,爱编程,爱运营,爱折腾。
坚持总结工作中遇到的技术问题,坚持记录工作中所所思所见,对于博客上面有不会的问题,可以加入qq群聊来问我:473819131。