简体   繁体   中英

Swift - force square photo from library and camera

I'm building an app and I need to FORCE the user to upload square pictures (just like Instagram does), however I'd like to avoid programming an interface from scratch as we're short in time.

It is important to note that the USER must CHOOSE which part of the image he/she wants to show, so cropping the image programatically without asking the user is out of the question.

I've managed to get this to work via camera, however via library I can't seem to force the user to use a square image. Here's the code I have:

func presentGallery(){
    // from library
    picker.allowsEditing = true
    picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    presentViewController(picker, animated: true, completion: nil)
}

Then on my imagepickercontroller:

    var chosenImage = info[UIImagePickerControllerEditedImage] as! UIImage 

However I don't get the desired result. It would be fine if the "minimum zoom" was to show 100% of the height of the image, or if I could add a white/black background to the top and bottom of the image.

Here's the problem: 在此处输入图片说明

Instead of something like this:

在此处输入图片说明

My app needs to work starting from iOS7.

You should do some sort of check to make sure that the picture is square if they're picking from their library.

Once you get the image (using imagePickerController didFinishPickingMediaWithInfo ), then get the image with [info objectForKey:UIImagePickerControllerOriginalImage]; . Once you've done this, perform the check:

if (image.size.height != image.size.width) // Show some alert

What might be an even better solution is creating a view which allows the user to pick any photo, and then choose a square part of the photo to import into your app, like Instagram does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM