#34 Protocol&Delegate-照片編輯App(1)

練習目的:模仿 iOS 的照片 App 編輯照片

分兩篇撰寫

第一篇:選取相簿照片Protocol&Delegate-UIImagePickerController、轉跳頁面/傳遞資料

第二篇:App編輯照片的功能(鏡像翻面、左右翻轉、改變照片比例:1:1、4:3&16:9&大小縮放、更改圖片背景顏色、儲存圖片)

App功能:

・選取相簿照片
・鏡像翻面
・左右翻轉
・改變照片比例:1:1、4:3、16:9 & 大小縮放
・更改圖片背景顏色
・儲存圖片

技術項目:

Protocol&Delegate

・UIImagePickerController

・UIColorPickerViewController

儲存 view 為 UIImage 圖片・UIGraphicsImageRenderer

轉跳頁面/傳遞資料・IBSegueAction & performSegue

・storyboard
・Swift 基本語法
・自訂 view controller 類別
・viewDidLoad
・IBOutlet & IBAction
・UIAlertController

1. StartViewController

#Protocol&Delegate-UIImagePickerController選照片

使用者選照片後,UIImagePickerController 找 delegate (代理人)幫忙,呼叫它的某個 function

func pickImage(){let controller = UIImagePickerController()//指定delegate為view controller(self)controller.delegate = selfcontroller.sourceType = .photoLibrarypresent(controller, animated: true)}

#遵從protocol UIImagePickerControllerDelegate&UINavigationControllerDelegate

想成為 UIImagePickerController 的 delegate,必須同時遵從protocol UIImagePickerControllerDelegate &UINavigationControllerDelegate

#將使用者選到的照片顯示在image view上

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {let image = info[.originalImage] as? UIImage //as?轉型成UIImage型別imageView.image = imagedismiss(animated: true, completion: nil)}

步驟整理:

  1. 使用者選照片後,UIImagePickerController 會呼叫 delegate 的imagePickerController(_:didFinishPickingMediaWithInfo:)
  2. 定義 protocol UIImagePickerControllerDelegate的imagePickerController(_:didFinishPickingMediaWithInfo:)
  3. info 裡有照片
  4. 將使用者選的照片顯示到image view 上

#設定顯示警告訊息和選單的 UIAlertController

@IBAction func addPhoto(_ sender: Any) {//設定視窗顯示的內容及樣式let choosecontroller = UIAlertController()//設定視窗顯示的內容及樣式let albumAction = UIAlertAction(title: "Album", style: .default) { [self] albumAction inself.pickImage()}choosecontroller.addAction(albumAction)let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)choosecontroller.addAction(cancelAction)present(choosecontroller, animated: true)}

#資料傳遞至下一頁

//資料傳遞至下一頁@IBSegueAction func editPic(_ coder: NSCoder) -> EditViewController? {let controller = EditViewController(coder: coder)controller?.enterPic = imageViewreturn controller}

2. EditViewController

#接收資料

var enterPic:UIImageView!
override func viewDidLoad() {
super.viewDidLoad()picImageView.image = enterPic.image}

--

--