Search code examples
iosswiftuiimagepickercontroller

Image to Initially Fill UIImagePickerController


In my iOS app I'd like to grab images from the photo library and crop them to square format. The UIImagePickerController takes care of this nicely, but there is one little problem: When I select a landscape-oriented photo from the library it does not fill the crop area (for portrait images it does). That allows the user to select a non-square area. Is there a way to force the image picker to fill the crop area vertically just like it does horizontally - without implemeting my own image picker?

My code:

class AddProfileViewController: UIViewController, UIGestureRecognizerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet weak var profileImageView: EnhancedImageView!
    let imagePicker = UIImagePickerController()

    override func viewDidLoad() {
        super.viewDidLoad()

        // ...

        imagePicker.delegate = self
    }

    func profileImageTapped() {
        imagePicker.allowsEditing = true
        imagePicker.sourceType = .PhotoLibrary
        presentViewController(imagePicker, animated: true, completion: nil)
    }

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
        // ...
    }

    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        dismissViewControllerAnimated(true, completion: nil)
    }
}

Selecting a landscape image, it looks like this:

image picker with horizontal image

Instead, I'd like the image to horizontally and vertically extend to the crop frame, so the image picker will always return a square image.


Solution

  • To close this question - here is how I solved it:

    Extending the image vertically to the boundaries does not seem to be possible with the standard image picker. Options are to create your own image picker or to use the following workaround which might be sufficient in most cases:

    If the user does not zoom in to any section of the image the center of the image is the best approximation to what the user wants, and you get the square image by cutting off equal-width slices on both sides.