LoginSignup
0
3

More than 1 year has passed since last update.

Swift画像トリミングアプリ

Last updated at Posted at 2022-05-25

SwiftのAddPackagesにてCropViewControllerを導入し、簡単に画像トリミング処理を実行してみる。
開発環境
xcode13
TOCropViewController

Swift Package Managerを利用してCocoapodを使わず、下記のようにインストール。
File->AddPackages->🔍にhttps://github.com/TimOliver/TOCropViewController.gitセット

下記追記
import CropViewController

スクリーンショット 2022-05-25 15.31.57.png

import UIKit
import CropViewController

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate,CropViewControllerDelegate {

    @IBOutlet weak var imageView: UIImageView!
    var image:UIImage?
    
    override func viewDidLoad() {
        super.viewDidLoad()
 
    }
    
    @IBAction func startView(_ sender: Any) {
        
        setImagePicker()
        
    }
    func setImagePicker(){
        let picker = UIImagePickerController()
        picker.sourceType = .photoLibrary
        picker.delegate = self
        present(picker, animated: true, completion: nil)
        
    }

    func cropViewController(_ cropViewController: CropViewController, didCropToImage image: UIImage, withRect cropRect: CGRect, angle: Int) {
        updateImageViewWithImage(image, fromCropViewController: cropViewController)
    }
        
    func updateImageViewWithImage(_ image: UIImage, fromCropViewController cropViewController: CropViewController) {
        imageView.image = image
        cropViewController.dismiss(animated: true, completion: nil)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let image = info[.originalImage] as! UIImage
        guard let pickerImage = (info[UIImagePickerController.InfoKey.originalImage] as? UIImage) else { return }
        
        let cropController = CropViewController(croppingStyle: .default, image: pickerImage)
        cropController.delegate = self
        cropController.customAspectRatio = CGSize(width: 100, height: 100)
        
        //今回は使わないボタン等を非表示にする。
        cropController.aspectRatioPickerButtonHidden = true
        cropController.resetAspectRatioEnabled = true
        cropController.rotateButtonsHidden = true
        
        //cropBoxのサイズを固定する。
        cropController.cropView.cropBoxResizeEnabled = true
        //pickerを閉じたら、cropControllerを表示する。
        picker.dismiss(animated: true) {
            self.present(cropController, animated: true, completion: nil)
        }
    }


}

画像セットボタンにてライブラリより画像選択し枠フレームにてトリミングし、Doneボタンにて実行。

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3