gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:35:42 25 4
gpt4 key购买 nike

这是我编写的用于在裁剪后调整图像大小的代码。我发现我重建了 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com