我想知道如何使用 UIImagePicker 从相机库中始终选择方形图像?
所以我设置了 imagePicker.allowsEditing = true
并且当我选择的图像足够大(大于正方形裁剪)时,选择的图像是正方形的。但是,当我选择的图像较小时,假设它是 748 x 466,即使正方形裁剪包围了包括顶部和底部黑色部分的图像,但选择的图像不包括黑色部分,因此它返回一个非正方形图片。我如何让它始终选择黑色的顶部和底部,使图像始终为正方形?
非常感谢您的帮助!
最佳答案
这里是使用 CoreGraphics 手动添加黑色区域的方法,在 UIImagePicker 委托(delegate)方法中添加:
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
。
关于ios - UIImagePicker : How to always pick square image from camera library?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33611310/