使用drawInRect调整图像大小,同时保持像Scale Aspect Fill一样的宽高比?

win*_*zed 10 uiimage ios swift

我想用drawInRect方法调整图像大小,但我还想保持正确的宽高比,同时完全填充给定的帧(如.ScaleAspectFill对UIViewContentMode所做的那样).任何人都有一个现成的答案吗?

这是我的代码(非常简单......):

func scaled100Image() -> UIImage {
    let newSize = CGSize(width: 100, height: 100)
    UIGraphicsBeginImageContext(newSize)
    self.pictures[0].drawInRect(CGRect(x: 0, y: 0, width: 100, height: 100))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}
Run Code Online (Sandbox Code Playgroud)

win*_*zed 24

好的,所以没有现成的答案......我为UIImage写了一个快速的扩展,如果你需要它可以随意使用它.

这里是:

extension UIImage {
    func drawInRectAspectFill(rect: CGRect) {
        let targetSize = rect.size
        if targetSize == CGSizeZero {
            return self.drawInRect(rect)
        }
        let widthRatio    = targetSize.width  / self.size.width
        let heightRatio   = targetSize.height / self.size.height
        let scalingFactor = max(widthRatio, heightRatio)
        let newSize = CGSize(width:  self.size.width  * scalingFactor,
                             height: self.size.height * scalingFactor)
        UIGraphicsBeginImageContext(targetSize)
        let origin = CGPoint(x: (targetSize.width  - newSize.width)  / 2, 
                             y: (targetSize.height - newSize.height) / 2)
        self.drawInRect(CGRect(origin: origin, size: newSize))
        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        scaledImage.drawInRect(rect)
    }
}
Run Code Online (Sandbox Code Playgroud)

所以在上面的例子中,你使用它:

self.pictures[0].drawInRectAspectFill(CGRect(x: 0, y: 0, width: 100, height: 100))
Run Code Online (Sandbox Code Playgroud)