Protocol&Delegate練習|照片編輯App
Published in
6 min readApr 15, 2021
UIGraphicsImageRenderer, instantiateViewController,UIImagePickerController
🌟APP功能:
・鏡像翻面
・左右翻轉
・更改圖片背景顏色
・儲存圖片
Protocol&Delegate
・UIImagePickerController (以此為例)
・UIColorPickerViewController
轉跳頁面/傳遞資料
・instantiateViewController
儲存 view 為 UIImage 圖片
・UIGraphicsImageRenderer
UIImagePickerController
生出UIImagePickerController,找delegate(代理對象)
//生成選照片的controller,指定delegate(代理對象)
func selectPhoto(sourceType:UIImagePickerController.SourceType) {
let imageController = UIImagePickerController()
imageController.sourceType = sourceType
imageController.delegate = self
present(imageController, animated: true, completion: nil)
}
成為delegate(代理對象)必須遵從protocol
Protocol: UIImagePickerControllerDelegate & UINavigationControllerDelegate
定義delegate的function(當使用者選擇照片後,執行該function)
//定義protocol function
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image = info[.originalImage] as? UIImage
imageView.image = image
//視窗關閉
dismiss(animated: true, completion: nil)
}
instantiateViewController
不需在storyboard上建立segue,轉跳至下一頁
if let editingViewController = storyboard?.instantiateViewController(identifier: "\(EditingViewController.self)", creator: { coder in EditingViewController.init(coder: coder, image: image!)
}) {
show(editingViewController, sender: nil)
}
UIGraphicsImageRenderer
照片編輯完,將UIView的畫面轉為UIImageView。
//產生 UIImageView的尺寸
let renderer = UIGraphicsImageRenderer(size: imageBackgroundView.bounds.size) //呼叫image(actions:)產生圖片
let image = renderer.image(actions: { (context) in //從UIView呼叫drawHierarchy(in:afterScreenUpdates:)將 containerView 的內容繪製成圖片
imageBackgroundView.drawHierarchy(in: imageBackgroundView.bounds, afterScreenUpdates: true)
})
UIActivityViewController 儲存圖片
let activityViewController = UIActivityViewController(activityItems: [image], applicationActivities: nil)
present(activityViewController, animated: true, completion: nil)
儲存圖片前須設定權限徵求使用者同意,否則將會閃退。.
GitHub