美文网首页
配置头像 Edit Profile Photo

配置头像 Edit Profile Photo

作者: DF_ | 来源:发表于2017-04-23 15:48 被阅读0次

Step 1: 拍照或者从相册里选择图片

首先 要import UIImagePickerControllerDelegate,
UINavigationControllerDelegate 两个类。

class ViewController: UIViewController,UIImagePickerControllerDelegate,
    UINavigationControllerDelegate{

    @IBOutlet weak var pickedImage: UIImageView!

再调用设置UIImagePickerController

func cameraAction() {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
            imagePicker.allowsEditing = false
            self.present(imagePicker,animated: true, completion: nil)
        }
        
    }
    
    func libraryAction() {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary){
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary;
            imagePicker.allowsEditing = false
            self.present(imagePicker,animated: true, completion: nil)
        }
    }

最后隐藏照片选择界面,并讲选中的照片设置在 UIImage 里

 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
         pickedImage.image = info[UIImagePickerControllerOriginalImage] as! UIImage 
        self.dismiss(animated: true, completion: nil)
    }

遇到的问题:
1 通过UIImagePickerControllerDelegate 拍照得到的照片的Orientation 并不是正的(通过UIImage.imageOrientation 查看)而从photo library 里面挑选的照片位置是正的。查阅资料发现iphone 拍照的时候默认的位置是 横着 home键在右侧。

解决:

// swift 3  code:
extension UIImage{
   
    func normalizedImage() -> UIImage {
        
        if (self.imageOrientation == UIImageOrientation.up) {
            return self;
        }
        
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
        let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
        self.draw(in: rect)
        
        let normalizedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext();
        return normalizedImage;
    }
}

(未完待续)

Reference:
http://stackoverflow.com/questions/5427656/ios-uiimagepickercontroller-result-image-orientation-after-upload/10611036#10611036
https://www.cnblogs.com/jiangyazhou/archive/2012/03/22/2412343.html

相关文章

网友评论

      本文标题:配置头像 Edit Profile Photo

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