#40 照片編輯 App — Part1,圖片旋轉、鏡射、剪裁功能

實現功能

  1. 圖片左右90度旋轉、鏡射
  2. 剪裁圖片
  3. 重設圖片

選取畫面

點擊按鈕後透過 present 呼叫 PHPickerConfiguration 顯示相簿並選取照片

使用 PHPickerConfiguration 選取照片

在 picker 事件內讀取圖片,並使用 instantiateViewController 傳照片給下一個頁面

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {picker.dismiss(animated: true)let itemProviders = results.map(\.itemProvider)// 選取單張寫法if let itemProvider = itemProviders.first,itemProvider.canLoadObject(ofClass: UIImage.self) {//let previousImage = self.imageViews.first?.imageitemProvider.loadObject(ofClass: UIImage.self) {[weak self] (image, error) inDispatchQueue.main.async {guard let self = self, let image = image as? UIImage else { return }//self.imageViews.first?.image = image//開啟 RetouchViewController 並把圖片傳過去if let retouchController = self.storyboard?.instantiateViewController(identifier: "retouchViewController", creator: { coder inRetouchViewController(coder: coder, editImage: image)}) {self.show(retouchController, sender: nil)}self.dismiss(animated: true, completion: nil)print("show retouchController")}}}}

使用 UICollectionView 顯示圖片結果

設定 CollectionView 的 collectionLayout 參數

//取得螢幕大小let fullScreenSize = UIScreen.main.bounds.size// collection view 初始化// sectionInset: 設定 Section 間距collectionLayout.sectionInset = UIEdgeInsets(top:5, left: 5, bottom: 5, right: 5)// itemSize: 設定每個 Cell 的大小collectionLayout.itemSize = CGSize(width: fullScreenSize.width/3-10, height: fullScreenSize.width/3-10)// minmumLineSpacing: Cell 的間距collectionLayout.minimumLineSpacing = 5// scrollDirection: 滑動的方向collectionLayout.scrollDirection = .vertical// headerReferenceSize: 設定 Section Header 的大小collectionLayout.headerReferenceSize = CGSize(width: fullScreenSize.width, height: 24)

使用 UICollectionView 也要記得實作 protocol ,UICollectionViewDataSource 與 UICollectionViewDelegate

編輯畫面

透過 Status 的模式切換,判斷現在是要旋轉或裁切圖片,使用touch event 偵測點擊行為,詳細程式碼請參考GitHub

UIGraphicsImageRenderer 儲存 view 為 UIImage 圖片

點選儲存後,透過 UIGraphicsImageRenderer 將圖片新增到 CollectionView 內,並刷新畫面

let renderer = UIGraphicsImageRenderer(size: editImageView!.bounds.size)let image = renderer.image(actions: { (context) in    editImageView!.drawHierarchy(in: editImageView!.bounds, afterScreenUpdates: true)})// 存入 imageCollection
imageCollection.append(image)// 回到第一頁
navigationController?.popToRootViewController(animated: true)

覆寫畫面刷新功能,儲存的照片才會顯示

// CollectionView 畫面刷新override func viewWillAppear(_ animated: Bool) {imageCollectionView.reloadData()//setIllustrationView()}

成果

GitHub

參考文章

--

--