这是我在裁剪后调整图像大小的代码。我发现我重建了CGImageRef来调整裁剪图像的大小。我猜必须有一种优化它的方法。又怎样?

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

最佳答案

这是我用来调整图像大小的功能。希望这是您想要的。

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

关于ios - Swift:如何优化裁剪后调整图像大小的代码?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36098254/

10-16 10:02