在我的iPhone应用程序中,我用相机拍了一张照片,然后我想把它调整为290*390像素。我用这个方法来调整图像的大小:
UIImage *newImage = [image _imageScaledToSize:CGSizeMake(290, 390)
interpolationQuality:1];
它工作得很好,但它是一个没有记录的功能,所以我不能再在iPhone OS4上使用它了。
所以…调整UIImage大小最简单的方法是什么?
如果你只想要一个更小的图像,不关心确切的大小:
+ (UIImage *)imageWithImage:(UIImage *)image scaledToScale:(CGFloat)scale
{
UIGraphicsBeginImageContextWithOptions(self.size, YES, scale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
[self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
将比例设置为0.25f将从800万相机中获得816 * 612的图像。
这里有一个UIImage+Scale的分类。
(兼容Swift 4) iOS 10+和iOS < 10解决方案(如果可能,使用UIGraphicsGetImageFromCurrentImageContext)
/// Resizes an image
///
/// - Parameter newSize: New size
/// - Returns: Resized image
func scaled(to newSize: CGSize) -> UIImage {
let rect = CGRect(origin: .zero, size: newSize)
if #available(iOS 10, *) {
let renderer = UIGraphicsImageRenderer(size: newSize)
return renderer.image { _ in
self.draw(in: rect)
}
} else {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
self.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
斯威夫特5:
func imageWithImage(_ image: UIImage?, scaledToSize newSize: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
image?.draw(in: CGRect(x: 0.0, y: 0.0, width: newSize.width, height: newSize.height))
let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
用法:
let img: UIImage? = imageWithImage(UIImage(named: "DefaultAvatar"), scaledToSize:CGSize(width: 20.0, height: 20.0))