Swift:如何优化我编写的代码以在裁剪后调整图像大小?

时间:2016-03-19 05:32:50

标签: ios swift swift2

这是我写的用于裁剪后调整图像大小的代码。我发现我重建了inspect来调整裁剪图像的大小。我想必须有一种方法来优化它。怎么样?

strftime

1 个答案:

答案 0 :(得分:0)

这是我用来调整图像大小的功能。希望这是你正在寻找的。

func ResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
    let size = image.size

    let widthRatio  = targetSize.width  / image.size.width
    let heightRatio = targetSize.height / image.size.height

    // Figure out orientation
    var newSize: CGSize
    if(widthRatio > heightRatio) {
        newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
    } else {
        newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
    }

    let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    image.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
}