ios – UIImagePicker:如何总是从相机库中挑选方形图像?

我想知道如何总是使用UI
ImagePicker从相机库中选择一个方形图像?

所以我设置了imagePicker.allowsEditing = true,当我选择的图像足够大(大于方形裁剪)时,拾取的图像是方形的.但是,当我选择的图像较小时,假设它是748乘466,即使方形裁剪包围包含顶部和底部黑色部分的图像,所选择的图像也不包括黑色部分,因此它返回一个非正方形图片.如何制作它以便总是选择黑色的顶部和底部,使图像始终是方形的?

非常感谢您的帮助!

最佳答案 以下是使用CoreGraphics手动添加黑色区域的方法,将它们添加到UIImagePicker委托方法中:

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()

然后使用imageYouWant.

点赞