gpt4 book ai didi

ios - UIImagePicker : How to always pick square image from camera library?

转载 作者:搜寻专家 更新时间:2023-10-31 19:34:26 24 4
gpt4 key购买 nike

我想知道如何使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com