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 |
03 | CGImageRef imgRef = image.CGImage; |
04 | CGFloat width = CGImageGetWidth(imgRef); |
05 | CGFloat height = CGImageGetHeight(imgRef); |
07 | if (width <= maxWidth && height <= maxHeight) |
12 | CGAffineTransform transform = CGAffineTransformIdentity; |
13 | CGRect bounds = CGRectMake(0, 0, width, height); |
15 | if (width > maxWidth || height > maxHeight) |
17 | CGFloat ratio = width/height; |
21 | bounds.size.width = maxWidth; |
22 | bounds.size.height = bounds.size.width / ratio; |
26 | bounds.size.height = maxHeight; |
27 | bounds.size.width = bounds.size.height * ratio; |
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); |
39 | UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext(); |
40 | UIGraphicsEndImageContext(); |
0 Comments