美文网首页
Swift相机相册的简单使用

Swift相机相册的简单使用

作者: 古月思吉 | 来源:发表于2018-09-22 16:22 被阅读0次

    1.配置权限:

    (1)相机权限:
    key:Privacy - Camera Usage Description
    value:拍摄照片需要获取相机权限
    (2)相册权限:
    key:Privacy - Photo Library Usage Description
    value:选择图片需要获取相册权限

    2.代码:

    //MARK: - UIImagePickerControllerDelegate,UINavigationControllerDelegate
    extension EditUserInfoController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
        
        func openCamera() {
            let picker = UIImagePickerController()
            picker.delegate = self
            if UIImagePickerController.isCameraDeviceAvailable(.rear) {
                picker.sourceType = .camera
                self.present(picker, animated: true, completion: nil)
            } else {
                HUDTool.showText(text: "暂无相机权限")
            }
        }
        
        func openAlbum() {
            let picker = UIImagePickerController()
            picker.delegate = self
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
                picker.sourceType = .photoLibrary
                self.present(picker, animated: true, completion: nil)
            } else {
                HUDTool.showText(text: "暂无相册权限")
            }
        }
        
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
            picker.dismiss(animated: true, completion: nil)
            let image = info[UIImagePickerControllerOriginalImage] as! UIImage
            self.portraitImageView.image = image
        }
        
        //裁剪图片
        func imageWithImageSimple(image:UIImage,scaledToSize newSize:CGSize)->UIImage{
            var width:CGFloat!
            var height:CGFloat!
            if image.size.width/newSize.width >= image.size.height / newSize.height{
                width = newSize.width
                height = image.size.height / (image.size.width/newSize.width)
            }else{
                height = newSize.height
                width = image.size.width / (image.size.height/newSize.height)
            }
            let sizeImageSmall = CGSize(width:width,height:height)
            //print(sizeImageSmall)
            UIGraphicsBeginImageContext(sizeImageSmall);
            image.draw(in: CGRect(x:0,y:0,width:sizeImageSmall.width,height:sizeImageSmall.height))
            let newImage:UIImage=UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext();
            return newImage;
        }
    }
    

    3.增加图片编辑功能:

    //允许图片编辑
    picker.allowsEditing = true
    
    //在 imagePickerController 代理方法中获取编辑后的图片
    let image = info[UIImagePickerControllerEditedImage] as! UIImage
    

    相关文章

      网友评论

          本文标题:Swift相机相册的简单使用

          本文链接:https://www.haomeiwen.com/subject/ehrxoftx.html