gabe
gabe

Reputation: 97

How can I crop an image before loading it to the view controller

In my view controller, my UIImageView is set to 370x370, when I load an image it currently stretches to fit the ImageView.

This is what I currently have for picking an image:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    // Runs when user is picking image from library
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        self.previewImageView.image = pickedImage
        self.selectImageButton.isEnabled = false
        self.selectImageButton.isHidden = true
        uploadImage(image: pickedImage)
        picker.dismiss(animated: true, completion: nil)
    }
}

I'm fairly new to Swift, what would be the best was to implement an image crop into my code?

Upvotes: 0

Views: 2857

Answers (1)

J Manuel
J Manuel

Reputation: 3070

When you call the ImagePicker function, set allowsEditing as true:

self.imagePicker.allowsEditing = true
self.imagePicker.sourceType = .camera
self.present(self.imagePicker, animated: true, completion: nil)

Another option, if you want a bit more customization, you can use this library: https://github.com/TimOliver/TOCropViewController

And in didFinishPickingMediaWithInfo, you do something like this:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage{
        dismiss(animated: true, completion: nil)
        let cropVC = TOCropViewController(image: pickedImage)
        cropVC.delegate = self
        cropVC.aspectRatioPickerButtonHidden = true
        cropVC.aspectRatioPreset = .presetSquare
        cropVC.aspectRatioLockEnabled = true
        cropVC.resetAspectRatioEnabled = false
        self.present(cropVC, animated: true, completion: nil)
    }
}

Upvotes: 3

Related Questions