現(xiàn)在的App里一般都會(huì)有設(shè)置頭像這個(gè)功能擎椰,網(wǎng)上介紹的大多是在舊版iOS上面使用Objective-C實(shí)現(xiàn)的。那么在最新的iOS 10中创肥,使用最新的Swift3如何實(shí)現(xiàn)呢达舒?下面通過實(shí)際代碼介紹。
設(shè)置Storyboard
Storyboard的布局非常簡單叹侄,一個(gè)UIImageView巩搏,兩個(gè)Button分別是從攝像頭獲取圖片和從相冊獲取圖片。
初始化
開始前需要給ViewController添加兩個(gè)delegates趾代,然后綁定UIImageView贯底,添加一個(gè)UIImagePickerController的實(shí)例,代碼如下:
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet var imageView: UIImageView!
let imagePicker = UIImagePickerController()
其次稽坤,還需要設(shè)置我們的ViewController作為UIImagePickerController的delegate:
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
}
通過攝像頭獲取圖片
通過上面的設(shè)置和初始化丈甸,接下來就可以通過iPhone的攝像頭獲取圖片了,我們將其封裝在一個(gè)函數(shù)里面:
func openCamera(){
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
}
從相冊中獲取圖片
從相冊中獲取圖片的方法和通過攝像頭獲取圖片的方法非常類似尿褪,代碼如下:
func openPhoto(){
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary;
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
}
顯示獲取到的圖片
通過以上兩個(gè)方法睦擂,我們獲取到了想要的圖片,最后就是將其顯示在UIImageView中杖玲,代碼如下:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
imageView.image = info[UIImagePickerControllerEditedImage] as! UIImage
self.dismiss(animated: true, completion: nil)
}
imagePickerController是一個(gè)回調(diào)方法顿仇,當(dāng)我們選擇好圖片之后,系統(tǒng)會(huì)調(diào)用這個(gè)方法摆马,info是一個(gè)字典臼闻,UIImagePickerControllerEditedImage這個(gè)key值對應(yīng)的value就是取到的編輯后的圖片,為UIImage類型囤采。
附:didFinishPickingMediaWithInfo字典對應(yīng)的key:value述呐。
let UIImagePickerControllerMediaType: String
Specifies the media type selected by the user.
let UIImagePickerControllerOriginalImage: String
Specifies the original, uncropped image selected by the user.
let UIImagePickerControllerEditedImage: String
Specifies an image edited by the user.
let UIImagePickerControllerCropRect: String
Specifies the cropping rectangle that was applied to the original image.
let UIImagePickerControllerMediaURL: String
Specifies the filesystem URL for the movie.
let UIImagePickerControllerReferenceURL: String
The Assets Library URL for the original version of the picked item.
let UIImagePickerControllerMediaMetadata: String
Metadata for a newly-captured photograph.
let UIImagePickerControllerLivePhoto: String
The Live Photo representation of the selected or captured photo.
本文作者:小池laucherish
本文出處:http://www.reibang.com/p/302a632950a0
轉(zhuǎn)載請?jiān)陂_頭注明作者詳細(xì)信息和本文出處。