UIImagePicker: How to always select a square image from the camera library?

I am wondering how can I always select a square image from the camera library using UIImagePicker?

So, I installed imagePicker.allowsEditing = true, and when the image that I select is large enough (more than a square crop), the selected image is square. But, when the image that I select is smaller, let's say it's 748 by 466, although the square load includes the image, including the upper and lower black parts, the selected image does not include black parts and therefore returns a non-square image. How to make sure that he always selects the black upper and lower parts, so the image is always square?

Many thanks for the help!

+4
source share
1 answer

Here, using CoreGraphics to manually add a black area, add them to the UIImagePicker delegate method:

let squareSideLength = image.size.width > image.size.height ? image.size.width : image.size.height
UIGraphicsBeginImageContextWithOptions(CGSizeMake(squareSideLength, squareSideLength), false, 1)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor)
CGContextFillRect(context, CGRectMake(0, 0, squareSideLength, squareSideLength))
image.drawInRect(CGRectMake((squareSideLength - image.size.width) / 2, (squareSideLength - image.size.height) / 2, image.size.width, image.size.height))
let imageYouWant = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

use imageYouWant, then.

+2
source

Source: https://habr.com/ru/post/1615054/


All Articles