This is a small snippet that shows how to resize a UIImage while maintaining aspect ratio.


01- (UIImage *)scaleImage:(UIImage *) image maxWidth:(float) maxWidth maxHeight:(float) maxHeight
02{
03 CGImageRef imgRef = image.CGImage;
04 CGFloat width = CGImageGetWidth(imgRef);
05 CGFloat height = CGImageGetHeight(imgRef);
06
07 if (width <= maxWidth && height <= maxHeight)
08 {
09 return image;
10 }
11
12 CGAffineTransform transform = CGAffineTransformIdentity;
13 CGRect bounds = CGRectMake(0, 0, width, height);
14
15 if (width > maxWidth || height > maxHeight)
16 {
17 CGFloat ratio = width/height;
18
19 if (ratio > 1)
20 {
21 bounds.size.width = maxWidth;
22 bounds.size.height = bounds.size.width / ratio;
23 }
24 else
25 {
26 bounds.size.height = maxHeight;
27 bounds.size.width = bounds.size.height * ratio;
28 }
29 }
30
31 CGFloat scaleRatio = bounds.size.width / width;
32 UIGraphicsBeginImageContext(bounds.size);
33 CGContextRef context = UIGraphicsGetCurrentContext();
34 CGContextScaleCTM(context, scaleRatio, -scaleRatio);
35 CGContextTranslateCTM(context, 0, -height);
36 CGContextConcatCTM(context, transform);
37 CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
38
39 UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
40 UIGraphicsEndImageContext();
41
42 return imageCopy;
43
44}