#35 Protocol&Delegate-照片編輯App(2)
Published in
8 min readSep 6, 2022
練習目的:模仿 iOS 的照片 App 編輯照片
分兩篇撰寫
第二篇:App編輯照片的功能(鏡像翻面、左右翻轉、改變照片比例:1:1、4:3&16:9&大小縮放、更改圖片背景顏色、儲存圖片)
第一篇:選取相簿照片Protocol&Delegate-UIImagePickerController、轉跳頁面/傳遞資料
EditViewController
#App功能
- 拉所需的IBOutlet、設定所需的變數
2. viewDidLoad
先隱藏沒有被點選的項目,設定顯示的圖片比例皆為預設的1:1
#iOS SDK 的 frame & bounds
3. 選擇改變方向
@IBAction func rotate(_ sender: UIButton) {turnleftButton.isHidden = falseturnrightButton.isHidden = falsemirrorButton.isHidden = false}
4. 方向向左轉
//改變照片方向向左轉@IBAction func leftRotate(_ sender: UIButton) {turnleftTimes += 1let oneDegree = CGFloat.pi / 180picImageView.transform = CGAffineTransform(rotationAngle: (oneDegree * -90)*CGFloat(turnleftTimes))}
5. 方向向右轉
//改變照片方向向右轉@IBAction func rightRotate(_ sender: UIButton) {turnrightTimes += 1let oneDegree = CGFloat.pi / 180picImageView.transform = CGAffineTransform(rotationAngle: (oneDegree * 90)*CGFloat(turnrightTimes))}
6. 鏡像轉
//改變照片方向鏡像轉@IBAction func mirrorRotate(_ sender: UIButton) {mirrorTimes *= -1picImageView.transform = CGAffineTransform(scaleX: CGFloat(mirrorTimes), y: 1)}
6. 選擇改變照片比例跟大小、改變照片比例、改變照片大小
(1)選擇改變照片比例跟大小
//改變照片比例跟大小@IBAction func changeScale(_ sender: UIButton) {sizeSegmentedControl.isHidden = falsezoominSlider.isHidden = false}
(2)改變照片比例
//改變照片比例@IBAction func changeScaleDetail(_ sender: Any) {let length: Int = 350var width: Intvar height: Int//設定原始顯示圖片比例為1:1switch sizeSegmentedControl.selectedSegmentIndex {case 0: //1:1width = lengthheight = lengthcase 1: //4:3width = lengthheight = Int(Double(length) / 4 * 3)case 2: //16:9width = lengthheight = Int(Double(length) / 16 * 9)default: //1:1width = lengthheight = length}picImageView.bounds.size = CGSize(width: width, height: height)}
(3)改變照片大小
//改變照片大小@IBAction func zoominout(_ sender: Any) {picImageView.transform = CGAffineTransform(scaleX: CGFloat(zoominSlider.value), y: CGFloat(zoominSlider.value))}
7. 改變背景顏色Protocol&Delegate-UIColorPickerViewController
#UIColorPickerViewController
//改變背景顏色@IBAction func changeColor(_ sender: Any) {let controller = UIColorPickerViewController()controller.delegate = selfpresent(controller, animated: true, completion: nil)}func colorPickerViewController(_ viewController: UIColorPickerViewController, didSelect color: UIColor, continuously: Bool) {containerView.backgroundColor = colordismiss(animated: true, completion: nil)}
8. 儲存照片 UIGraphicsImageRenderer
//儲存照片@IBAction func saveEditedPhoto(_ sender: Any) {//利用UIGraphicsImageRenderer將view變成UIImagelet renderer = UIGraphicsImageRenderer(size: containerView.bounds.size)//呼叫image(actions:)產生圖片let editimage = renderer.image(actions: { context incontainerView.drawHierarchy(in: containerView.bounds, afterScreenUpdates: true)})//利用UIActivityViewController分享圖片let activityViewController = UIActivityViewController(activityItems: [editimage], applicationActivities: nil)present(activityViewController, animated: true, completion: nil)}
#Info 頁面加權限請求的文字
完整程式碼: