uni-app 实现自定义拍摄头像功能

  • Post author:
  • Post category:其他


<!-- 头像选择框自定义 -->
		<view class="" v-if="showHeader" style="position: fixed;top: 0;left: 0;z-index: 777;width: 100%;height: 100vh;background-color: #FFFFFF;">
			<camera binderror="handleCameraError" device-position="devicePosition" flash="off" style="width: 100%; height: 70vh;" v-if="authCamera">
				    <cover-image  :src="header" style="width: 100%;height: 60vh;margin-top:5vh ;"></cover-image>
				
			</camera>
			<button type="warn" @tap="takePhotoByHead" style="width: 100%;margin-top: 5vh;">拍照</button>
			<!-- <button type="primary" @tap="reverseCamera">摄像头切换</button> -->
			<view class="error-handler" v-if="!authCamera">
			    <button class="nobtn" openType="openSetting">打开相机授权</button>
			</view>
		</view>

data(){
    return {
        authCamera:false,
        showHeader :false,
        ctxHeader:null,
}
},
onShow: function () {
			var that = this;
			//获取相机权限
			uni.getSetting({
				success(res) {
				 if (res.authSetting["scope.camera"]) {
							that.authCamera = true
				  } else {
					  that.authCamera = false
				  }
				}
			})
		 },
methods: {
			//拍摄头像
			takePhotoByHead(){
				this.showHeader = true//开启拍照
				let _thats = this;
				this.ctxHeader = uni.createCameraContext();
				this.ctxHeader.takePhoto({
					quality: 'high',
					success: (res) => {
						uni.compressImage({
							src: res.tempImagePath,
							quality: 90,//压缩比例
							success: ress => {
								_thats.newPath  = ress.tempFilePath;//图片
								_thats.showHeader = false;//关闭拍照
							}
						})
						
						
					}
				});
			},
			handleCameraError(){
			    uni.showToast({
			      title:'用户拒绝使用摄像头',
			      icon: 'none'
			    })
			  },
			  reverseCamera(){
			     this.devicePosition = "back" === this.devicePosition ? "front" : "back"
			  },
}

头像框:



版权声明:本文为qq_39197547原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。