Swift 画像トリミング

全体集合写真で自分だけトリミングされました。海紫です!

 

今回は、Swiftで画像をトリミングする方法を紹介します。

TOCropViewControllerというライブラリを使用します。

公式 https://github.com/TimOliver/TOCropViewController

下記のようにUIImageを用意し、cropViewControllerのインスタンスを作成し遷移処理をする事で画像をトリミングする画面に遷移します。

let image: UIImage = ............. // UIImage() 自分で用意
 
 let cropViewController = CropViewController(image: image)
 		//画像のアスペクト比はIBにあるimageViewに合わせる
         cropViewController.customAspectRatio = self.imageView.frame.size
         //画像比率を選択できるボタンの非表示
         cropViewController.aspectRatioPickerButtonHidden = true
         cropViewController.resetAspectRatioEnabled = false
         //画像を回転できるボタンの非表示
         cropViewController.rotateButtonsHidden = true
         //画像の比率を変えられなくする
         cropViewController.cropView.cropBoxResizeEnabled = false
         cropViewController.delegate = self
         
         
         self.present(cropViewController, animated: true, completion: nil)

上記でdelegateを実装しており、画像をトリミングした後に処理が呼ばれるためdelegate処理を実装して行きます

extension ViewController: CropViewControllerDelegate{
 	//画像をトリミング後に呼ばれるメソッド
     func cropViewController(_ cropViewController: CropViewController, didCropToImage image: UIImage, withRect cropRect: CGRect, angle: Int) {
         self.imageView.image = image
         self.dismiss(animated: true, completion: nil)
     }
     //キャンセルが押された時
     func cropViewController(_ cropViewController: CropViewController, didFinishCancelled cancelled: Bool) {
         self.dismiss(animated: true, completion: nil)
     }
 }

取得した画像を表示したり、保存したりする事でトリミングした画像を扱う事が出来ます。

まとめ

画像をトリミングする方法を紹介しました。

トリミングをする際のオプションは、載せてますがもっと知りたい方は公式を参照してみて下さい!

ライブラリを使用して開発時間を短縮(о´∀`о)