#95 卡娜赫拉照片編輯 App
龜速行進終於爬到 protocol & delegate 這個重要的題目….
今天來做照片編輯 App !
這次使用到的技巧有:
1. 使用UIImagePickerController選照片
2. 使用CGAffineTransform 旋轉畫面
3. 使用 UIColorPickerViewController 選擇筆刷顏色,在相片上留下美麗的文字
4. 使用 UIGraphicsImageRenderer 將 view 變成圖片,儲存到 iphone 內的 photo album
操作細節:
其實照著上面的指示一步步寫完程式,這次的作業還算順利,
唯一困難竟然是卡在「圖形切割」,
一開始寫完程式還是一直無法順利裁切形狀,
最後發現兩個重點:一個是圖形要設定 “Aspect fill”,
另一個是不能設定圖片的 AutoLayout!
否則怎麼樣都不成功。(彼得潘說之後會學怎麼寫程式改AutoLayout…)
圖形切割的部分程式碼:
//先在畫面一開始設定containerView尺寸=圖片尺寸
override func viewDidLoad() {
super.viewDidLoad()
height = containerView.bounds.height
width = containerView.bounds.width
imageSelected.frame = containerView.bounds
}//Original Size
@IBAction func originalSize(_ sender: Any) {
imageSelected.frame = containerView.bounds
}//圖形切割成1:1
@IBAction func size1(_ sender: Any) {
height = containerView.bounds.height
imageSelected.bounds.size = CGSize(width: height, height: height)
}//圖形切割成3:4
@IBAction func size2(_ sender: Any) {
height = containerView.bounds.height
imageSelected.bounds.size = CGSize(width: height*3/4, height: height)
}
第二個重點是輸入文字,使用 UIColorPickerViewController 選擇筆刷顏色。
先遵從 protocol UIColorPickerViewControllerDelegate:
@IBAction func addWords(_ sender: Any) {
let controller = UIColorPickerViewController()
controller.delegate = self
present(controller, animated: true, completion: nil)
}
接著利用選取的顏色,設為Label的顏色:
func colorPickerViewControllerDidSelectColor(_ viewController: UIColorPickerViewController) {
wordLabel.textColor = viewController.selectedColor
}//輸入 Text 後按"Go!"按鈕顯示在 Label 上
@IBAction func finishKeyIn(_ sender: Any) {
wordLabel.text = keyinText.text
}
等到圖片編輯完成,最後一個步驟就是利用 UIGraphicsImageRenderer 將 view 變成圖片:
@IBAction func savePhoto(_ sender: Any) {
let renderer = UIGraphicsImageRenderer(size: containerView.bounds.size)
let image = renderer.image { (UIGraphicsImageRendererContext) in
containerView.drawHierarchy(in: containerView.bounds, afterScreenUpdates: true)
}
let activityViewController = UIActivityViewController(activityItems: [image], applicationActivities: nil)
present(activityViewController, animated: true, completion: nil)
}
這樣就完成照片編輯器啦!可以在相簿裡看到儲存完成的圖片了~