简体   繁体   中英

Swift: How to Optimize the code I wrote to resize an image after cropping?

Here's the code I wrote to resize an image after cropping. I find that I rebuild a CGImageRef to resize the cropped image. I guess there must be a way to optimize it. So how?

let imgRef: CGImageRef = CGImageCreateWithImageInRect(img.CGImage, rect)!
let croppedImg = UIImage(CGImage: imgRef, scale: 1, orientation: .Up)

let imgSize = CGSize(width: Conf.Size.avatarSize.width, height: Conf.Size.avatarSize.width)

UIGraphicsBeginImageContextWithOptions(imgSize, false, 1.0)
croppedImg.drawInRect(CGRect(origin: CGPointZero, size: imgSize))
let savingImgContext = UIGraphicsGetCurrentContext()
UIGraphicsEndImageContext()

if let savingImgRef: CGImageRef = CGBitmapContextCreateImage(savingImgContext) {
    let savingImg = UIImage(CGImage: savingImgRef, scale: 1, orientation: .Up)
    UIImageWriteToSavedPhotosAlbum(savingImg, nil, nil, nil)
}

Here's a function I use to resize images. Hopefully it is what you are looking for.

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!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM