这个问题确实是其他几个问题的重复,包括:How to crop the UIImage?,但由于我花了一段时间才找到解决方案,我将再次交叉发布。
在我寻求更容易理解(并用 Swift 编写)的解决方案时,我得出了以下结论:
我希望能够根据纵横比从区域裁剪,并根据外部边界范围缩放到大小。这是我的变体:
import AVFoundation
import ImageIO
class Image {
class func crop(image:UIImage, crop source:CGRect, aspect:CGSize, outputExtent:CGSize) -> UIImage {
let sourceRect = AVMakeRectWithAspectRatioInsideRect(aspect, source)
let targetRect = AVMakeRectWithAspectRatioInsideRect(aspect, CGRect(origin: CGPointZero, size: outputExtent))
let opaque = true, deviceScale:CGFloat = 0.0 // use scale of device's main screen
UIGraphicsBeginImageContextWithOptions(targetRect.size, opaque, deviceScale)
let scale = max(
targetRect.size.width / sourceRect.size.width,
targetRect.size.height / sourceRect.size.height)
let drawRect = CGRect(origin: -sourceRect.origin * scale, size: image.size * scale)
image.drawInRect(drawRect)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
}
有几件事让我感到困惑,裁剪和调整大小的不同问题。裁剪由您传递给 drawInRect 的矩形的原点处理,缩放由大小部分处理。在我的情况下,我需要将源上的裁剪矩形的大小与相同纵横比的输出矩形相关联。然后输出/输入比例因子,这需要应用于drawRect(传递给drawInRect)。
需要注意的是,这种方法有效地假设您正在绘制的图像大于图像上下文。我没有对此进行测试,但我认为您可以使用此代码来处理裁剪/缩放,但将比例参数明确定义为上述比例参数。默认情况下,UIKit 根据屏幕分辨率应用乘数。
最后,应该注意的是,这种 UIKit 方法比 CoreGraphics / Quartz 和 Core Image 方法级别更高,并且似乎可以处理图像方向问题。还值得一提的是,它非常快,仅次于 ImageIO,根据这里的这篇文章:http://nshipster.com/image-resizing/