在我的iPhone应用程序中,我用相机拍了一张照片,然后我想把它调整为290*390像素。我用这个方法来调整图像的大小:
UIImage *newImage = [image _imageScaledToSize:CGSizeMake(290, 390)
interpolationQuality:1];
它工作得很好,但它是一个没有记录的功能,所以我不能再在iPhone OS4上使用它了。
所以…调整UIImage大小最简单的方法是什么?
以下是斯威夫特版的保罗·林奇的回答
func imageWithImage(image:UIImage, scaledToSize newSize:CGSize) -> UIImage{
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
作为延伸:
public extension UIImage {
func copy(newSize: CGSize, retina: Bool = true) -> UIImage? {
// In next line, pass 0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
// Pass 1 to force exact pixel size.
UIGraphicsBeginImageContextWithOptions(
/* size: */ newSize,
/* opaque: */ false,
/* scale: */ retina ? 0 : 1
)
defer { UIGraphicsEndImageContext() }
self.draw(in: CGRect(origin: .zero, size: newSize))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
我也见过这样做(我在UIButtons的正常和选定状态下使用,因为按钮不会调整大小来适应)。功劳归于原作者。
首先创建一个空的。h和。m文件,分别命名为uiimageresize .h和uiimageresize .m
// Put this in UIImageResizing.h
@interface UIImage (Resize)
- (UIImage*)scaleToSize:(CGSize)size;
@end
// Put this in UIImageResizing.m
@implementation UIImage (Resize)
- (UIImage*)scaleToSize:(CGSize)size {
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0.0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, size.width, size.height), self.CGImage);
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
@end
将.h文件包含在你将要使用该函数的.m文件中,然后像这样调用它:
UIImage* image = [UIImage imageNamed:@"largeImage.png"];
UIImage* smallImage = [image scaleToSize:CGSizeMake(100.0f,100.0f)];
对Paul代码的改进将使你在带有视网膜显示屏的iPhone上获得清晰的高分辨率图像。否则按比例缩小时就会模糊。
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
if ([[UIScreen mainScreen] scale] == 2.0) {
UIGraphicsBeginImageContextWithOptions(newSize, YES, 2.0);
} else {
UIGraphicsBeginImageContext(newSize);
}
} else {
UIGraphicsBeginImageContext(newSize);
}
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}