在我的iPhone应用程序中,我用相机拍了一张照片,然后我想把它调整为290*390像素。我用这个方法来调整图像的大小:
UIImage *newImage = [image _imageScaledToSize:CGSizeMake(290, 390)
interpolationQuality:1];
它工作得很好,但它是一个没有记录的功能,所以我不能再在iPhone OS4上使用它了。
所以…调整UIImage大小最简单的方法是什么?
最简单的方法是设置UIImageView的框架,并将contentMode设置为其中一个调整大小的选项。
或者你可以使用这个实用工具方法,如果你真的需要调整图像的大小:
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
//UIGraphicsBeginImageContext(newSize);
// In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
// Pass 1.0 to force exact pixel size.
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
使用示例:
#import "MYUtil.h"
…
UIImage *myIcon = [MYUtil imageWithImage:myUIImageInstance scaledToSize:CGSizeMake(20, 20)];
我也见过这样做(我在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;
}
如果你只想要一个更小的图像,不关心确切的大小:
+ (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的分类。
以下是斯威夫特版的保罗·林奇的回答
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()
}
}
下面是iwasrob对上述类别的修改。它保持原始图像的纵横比,而不是扭曲它。
- (UIImage*)scaleToSizeKeepAspect:(CGSize)size {
UIGraphicsBeginImageContext(size);
CGFloat ws = size.width/self.size.width;
CGFloat hs = size.height/self.size.height;
if (ws > hs) {
ws = hs/ws;
hs = 1.0;
} else {
hs = ws/hs;
ws = 1.0;
}
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0.0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(size.width/2-(size.width*ws)/2,
size.height/2-(size.height*hs)/2, size.width*ws,
size.height*hs), self.CGImage);
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
我在苹果自己的例子中找到了一个UIImage的类别,它做了同样的技巧。这是链接:https://developer.apple.com/library/ios/samplecode/sc2273/Listings/AirDropSample_UIImage_Resize_m.html。
你只需要改变电话号码:
UIGraphicsBeginImageContextWithOptions(newSize, YES, 2.0);
in imageWithImage:scaledToSize:inRect: with
UIGraphicsBeginImageContextWithOptions(newSize, NO, 2.0);
为了考虑图像中的alpha通道。
这里是我的一些冗长的Swift代码
func scaleImage(image:UIImage, toSize:CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(toSize, false, 0.0);
let aspectRatioAwareSize = self.aspectRatioAwareSize(image.size, boxSize: toSize, useLetterBox: false)
let leftMargin = (toSize.width - aspectRatioAwareSize.width) * 0.5
let topMargin = (toSize.height - aspectRatioAwareSize.height) * 0.5
image.drawInRect(CGRectMake(leftMargin, topMargin, aspectRatioAwareSize.width , aspectRatioAwareSize.height))
let retVal = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return retVal
}
func aspectRatioAwareSize(imageSize: CGSize, boxSize: CGSize, useLetterBox: Bool) -> CGSize {
// aspect ratio aware size
// http://stackoverflow.com/a/6565988/8047
let imageWidth = imageSize.width
let imageHeight = imageSize.height
let containerWidth = boxSize.width
let containerHeight = boxSize.height
let imageAspectRatio = imageWidth/imageHeight
let containerAspectRatio = containerWidth/containerHeight
let retVal : CGSize
// use the else at your own risk: it seems to work, but I don't know
// the math
if (useLetterBox) {
retVal = containerAspectRatio > imageAspectRatio ? CGSizeMake(imageWidth * containerHeight / imageHeight, containerHeight) : CGSizeMake(containerWidth, imageHeight * containerWidth / imageWidth)
} else {
retVal = containerAspectRatio < imageAspectRatio ? CGSizeMake(imageWidth * containerHeight / imageHeight, containerHeight) : CGSizeMake(containerWidth, imageHeight * containerWidth / imageWidth)
}
return retVal
}
使用这个扩展
extension UIImage {
public func resize(size:CGSize, completionHandler:(resizedImage:UIImage, data:NSData?)->()) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), { () -> Void in
let newSize:CGSize = size
let rect = CGRectMake(0, 0, newSize.width, newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
self.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let imageData = UIImageJPEGRepresentation(newImage, 0.5)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler(resizedImage: newImage, data:imageData)
})
})
}
}
为什么这么复杂?我认为使用系统API可以达到同样的效果:
UIImage *largeImage;
CGFloat ratio = 0.4; // you want to get a new image that is 40% the size of large image.
UIImage *newImage = [UIImage imageWithCGImage:largeImage.CGImage
scale:1/ratio
orientation:largeImage.imageOrientation];
// notice the second argument, it is 1/ratio, not ratio.
唯一的问题是你应该传递目标比率的倒数作为第二个参数,因为根据文档,第二个参数指定原始图像与新缩放图像的比率。
Rogerio Chaves的回答是一个快速扩展
func scaledTo(size: CGSize) -> UIImage{
UIGraphicsBeginImageContextWithOptions(size, false, 0.0);
self.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
还有额外的好处
func scaledTo(height: CGFloat) -> UIImage{
let width = height*self.size.width/self.size.height
return scaledTo(size: CGSize(width: width, height: height))
}
@Paul Lynch的回答很好,但它会改变图像比例。
如果你不想改变图像比例,并且仍然希望新的图像适合新的大小,试试这个。
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
// calculate a new size which ratio is same to original image
CGFloat ratioW = image.size.width / newSize.width;
CGFloat ratioH = image.size.height / newSize.height;
CGFloat ratio = image.size.width / image.size.height;
CGSize showSize = CGSizeZero;
if (ratioW > 1 && ratioH > 1) {
if (ratioW > ratioH) {
showSize.width = newSize.width;
showSize.height = showSize.width / ratio;
} else {
showSize.height = newSize.height;
showSize.width = showSize.height * ratio;
}
} else if (ratioW > 1) {
showSize.width = showSize.width;
showSize.height = showSize.width / ratio;
} else if (ratioH > 1) {
showSize.height = showSize.height;
showSize.width = showSize.height * ratio;
}
//UIGraphicsBeginImageContext(newSize);
// In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
// Pass 1.0 to force exact pixel size.
UIGraphicsBeginImageContextWithOptions(showSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, showSize.width, showSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;}
正确的Swift 3.0 iOS 10+解决方案:使用ImageRenderer和闭包语法:
func imageWith(newSize: CGSize) -> UIImage {
let image = UIGraphicsImageRenderer(size: newSize).image { _ in
draw(in: CGRect(origin: .zero, size: newSize))
}
return image.withRenderingMode(renderingMode)
}
这是Objective-C版本:
@implementation UIImage (ResizeCategory)
- (UIImage *)imageWithSize:(CGSize)newSize
{
UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:newSize];
UIImage *image = [renderer imageWithActions:^(UIGraphicsImageRendererContext*_Nonnull myContext) {
[self drawInRect:(CGRect) {.origin = CGPointZero, .size = newSize}];
}];
return [image imageWithRenderingMode:self.renderingMode];
}
@end
Swift 3.0带有故障安全选项(在错误的情况下返回原始图像):
func resize(image: UIImage, toSize size: CGSize) -> UIImage{
UIGraphicsBeginImageContextWithOptions(size,false,1.0)
image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
if let resizedImage = UIGraphicsGetImageFromCurrentImageContext() {
UIGraphicsEndImageContext()
return resizedImage
}
UIGraphicsEndImageContext()
return image
}
这是一个与Swift 3和Swift 4兼容的UIImage扩展,它可以将图像缩放到给定的大小
extension UIImage {
func scaledImage(withSize size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height))
return UIGraphicsGetImageFromCurrentImageContext()!
}
func scaleImageToFitSize(size: CGSize) -> UIImage {
let aspect = self.size.width / self.size.height
if size.width / aspect <= size.height {
return scaledImage(withSize: CGSize(width: size.width, height: size.width / aspect))
} else {
return scaledImage(withSize: CGSize(width: size.height * aspect, height: size.height))
}
}
}
示例使用
let image = UIImage(named: "apple")
let scaledImage = image.scaleImageToFitSize(size: CGSize(width: 45.0, height: 45.0))
我发现在你的Swift 3项目中很难找到一个开箱即用的答案。其他答案的主要问题是他们不尊重图像的alpha通道。这是我在我的项目中使用的技巧。
extension UIImage {
func scaledToFit(toSize newSize: CGSize) -> UIImage {
if (size.width < newSize.width && size.height < newSize.height) {
return copy() as! UIImage
}
let widthScale = newSize.width / size.width
let heightScale = newSize.height / size.height
let scaleFactor = widthScale < heightScale ? widthScale : heightScale
let scaledSize = CGSize(width: size.width * scaleFactor, height: size.height * scaleFactor)
return self.scaled(toSize: scaledSize, in: CGRect(x: 0.0, y: 0.0, width: scaledSize.width, height: scaledSize.height))
}
func scaled(toSize newSize: CGSize, in rect: CGRect) -> UIImage {
if UIScreen.main.scale == 2.0 {
UIGraphicsBeginImageContextWithOptions(newSize, !hasAlphaChannel, 2.0)
}
else {
UIGraphicsBeginImageContext(newSize)
}
draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage ?? UIImage()
}
var hasAlphaChannel: Bool {
guard let alpha = cgImage?.alphaInfo else {
return false
}
return alpha == CGImageAlphaInfo.first ||
alpha == CGImageAlphaInfo.last ||
alpha == CGImageAlphaInfo.premultipliedFirst ||
alpha == CGImageAlphaInfo.premultipliedLast
}
}
用法示例:
override func viewDidLoad() {
super.viewDidLoad()
let size = CGSize(width: 14.0, height: 14.0)
if let image = UIImage(named: "barbell")?.scaledToFit(toSize: size) {
let imageView = UIImageView(image: image)
imageView.center = CGPoint(x: 100, y: 100)
view.addSubview(imageView)
}
}
这段代码重写了Apple的扩展,增加了对有和没有alpha通道的图像的支持。
作为进一步的阅读,我建议查看这篇文章,了解不同的图像调整技术。目前的方法提供了不错的性能,它操作高级api,易于理解。我建议坚持使用它,除非您发现图像大小调整是性能的瓶颈。
(兼容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!
}
}
快速解决方案的拉伸填充,方面填补和方面适合
extension UIImage {
enum ContentMode {
case contentFill
case contentAspectFill
case contentAspectFit
}
func resize(withSize size: CGSize, contentMode: ContentMode = .contentAspectFill) -> UIImage? {
let aspectWidth = size.width / self.size.width
let aspectHeight = size.height / self.size.height
switch contentMode {
case .contentFill:
return resize(withSize: size)
case .contentAspectFit:
let aspectRatio = min(aspectWidth, aspectHeight)
return resize(withSize: CGSize(width: self.size.width * aspectRatio, height: self.size.height * aspectRatio))
case .contentAspectFill:
let aspectRatio = max(aspectWidth, aspectHeight)
return resize(withSize: CGSize(width: self.size.width * aspectRatio, height: self.size.height * aspectRatio))
}
}
private func resize(withSize size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, self.scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
要使用,您可以执行以下操作:
let image = UIImage(named: "image.png")!
let newImage = image.resize(withSize: CGSize(width: 200, height: 150), contentMode: .contentAspectFill)
感谢abdullahselek最初的解决方案。
有效的方法,不拉伸图像Swift 4
// Method to resize image
func resize(image: UIImage, toScaleSize:CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(toScaleSize, true, image.scale)
image.draw(in: CGRect(x: 0, y: 0, width: toScaleSize.width, height: toScaleSize.height))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
//调用方法
let resizedImage = self.resize(image: UIImage(named: "YourImageName")!, toScaleSize: CGSize(width: 290, height: 390))
给我的萨玛瑞恩同胞们,这是萨玛琳。iOS c#版本的@Paul Lynch回答。
private UIImage ResizeImage(UIImage image, CGSize newSize)
{
UIGraphics.BeginImageContextWithOptions(newSize, false, 0.0f);
image.Draw(new CGRect(0, 0, newSize.Width, newSize.Height));
UIImage newImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
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))