一、創建項目
這個很簡單,創建好了看下面的就行了
二、添加權限
拍照和獲取相冊都需要先設置權限
三、佈局
實現一個簡單的佈局,同一個界面,一個按鈕 Button,一張圖片 ImageView
四、實現代碼
1、要繼承 UIImagePickerControllerDelegate, UINavigationControllerDelegate
2、拍照或從相冊選擇圖片都是通過 UIImagePickerController.init()
設置 sourceType = .camera 是拍照
設置 sourceType = .photoLibrary 是從相冊選擇圖片
3、相冊選擇或拍照都是通過 imagePickerController 方法返回,如果對圖片還要做處理也可以在這裏做
import UIKit
class ImageController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
//圖片展示
@IBOutlet weak var image: UIImageView!
var takingPicture:UIImagePickerController!
//點擊按鈕彈出拍照、相冊的選擇框
@IBAction func getImage(_ sender: Any) {
let actionSheetController = UIAlertController()
let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel) { (alertAction) -> Void in
print("Tap 取消 Button")
}
let takingPicturesAction = UIAlertAction(title: "拍照", style: UIAlertAction.Style.destructive) { (alertAction) -> Void in
self.getImageGo(type: 1)
}
let photoAlbumAction = UIAlertAction(title: "相冊", style: UIAlertAction.Style.default) { (alertAction) -> Void in
self.getImageGo(type: 2)
}
actionSheetController.addAction(cancelAction)
actionSheetController.addAction(takingPicturesAction)
actionSheetController.addAction(photoAlbumAction)
//iPad設備浮動層設置錨點
actionSheetController.popoverPresentationController?.sourceView = sender as? UIView
//顯示
self.present(actionSheetController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//去拍照或者去相冊選擇圖片
func getImageGo(type:Int){
takingPicture = UIImagePickerController.init()
if(type==1){
takingPicture.sourceType = .camera
//拍照時是否顯示工具欄
//takingPicture.showsCameraControls = true
}else if(type==2){
takingPicture.sourceType = .photoLibrary
}
//是否截取,設置爲true在獲取圖片後可以將其截取成正方形
takingPicture.allowsEditing = false
takingPicture.delegate = self
present(takingPicture, animated: true, completion: nil)
}
//拍照或是相冊選擇返回的圖片
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
takingPicture.dismiss(animated: true, completion: nil)
if(takingPicture.allowsEditing == false){
//原圖
image.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
}else{
//截圖
image.image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
}
}
}
五、拍照界面改成中文
完成上面的步驟就能夠實現簡單的通過拍照、相冊獲取圖片了
但是,我們會發現,選擇拍照時,上面的操作步驟文字都是英文的,我們可以把它改成中文
如下圖所示,選中項目 -> PEOJECT -> Info -> Localization
點擊 + 將 Chinese,Simplified 添加到 Localization 重新運行項目就可以看到拍照界面都是中文了