UIImage 调整大小扩展
UIImage Resize Extension
我做了一个扩展,可以让我调整 UIImage 的大小,但我想知道我是否正确地调用了它。扩展名在它自己的文件中,如下所示:
extension UIImage {
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 what our orientation is, and use that to form the rectangle
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)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
然后我这样称呼它:
img.resizeImage(image: img, targetSize: CGSize(width: 200.0, height: 200.0))
其中 img 是一个 UIImage。
但是,我在 UIImage 上调用一个函数,但也将其作为参数传入,这对我来说似乎很奇怪。这是正确的方法还是有更简洁的方法?
您正在失去使用扩展程序的便利。在这里检查:
https://www.hackingwithswift.com/read/24/2/creating-a-swift-extension
主要思想是您需要删除第一个参数并在函数代码中使用 self
我做了一个扩展,可以让我调整 UIImage 的大小,但我想知道我是否正确地调用了它。扩展名在它自己的文件中,如下所示:
extension UIImage {
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 what our orientation is, and use that to form the rectangle
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)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
然后我这样称呼它:
img.resizeImage(image: img, targetSize: CGSize(width: 200.0, height: 200.0))
其中 img 是一个 UIImage。 但是,我在 UIImage 上调用一个函数,但也将其作为参数传入,这对我来说似乎很奇怪。这是正确的方法还是有更简洁的方法?
您正在失去使用扩展程序的便利。在这里检查: https://www.hackingwithswift.com/read/24/2/creating-a-swift-extension
主要思想是您需要删除第一个参数并在函数代码中使用 self