Created
July 9, 2014 08:35
-
-
Save HamGuy/5a7cc110d7f52ef3f98c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Resizes the image according to the given content mode, taking into account the image's orientation | |
- (UIImage *)resizedImageWithContentMode:(UIViewContentMode)contentMode imageToScale:(UIImage*)imageToScale bounds:(CGSize)bounds interpolationQuality:(CGInterpolationQuality)quality { | |
//Get the size we want to scale it to | |
CGFloat horizontalRatio = bounds.width / imageToScale.size.width; | |
CGFloat verticalRatio = bounds.height / imageToScale.size.height; | |
CGFloat ratio; | |
switch (contentMode) { | |
case UIViewContentModeScaleAspectFill: | |
ratio = MAX(horizontalRatio, verticalRatio); | |
break; | |
case UIViewContentModeScaleAspectFit: | |
ratio = MIN(horizontalRatio, verticalRatio); | |
break; | |
default: | |
[NSException raise:NSInvalidArgumentException format:@"Unsupported content mode: %d", contentMode]; | |
} | |
//...and here it is | |
CGSize newSize = CGSizeMake(imageToScale.size.width * ratio, imageToScale.size.height * ratio); | |
//start scaling it | |
CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height)); | |
CGImageRef imageRef = imageToScale.CGImage; | |
CGContextRef bitmap = CGBitmapContextCreate(NULL, | |
newRect.size.width, | |
newRect.size.height, | |
CGImageGetBitsPerComponent(imageRef), | |
0, | |
CGImageGetColorSpace(imageRef), | |
CGImageGetBitmapInfo(imageRef)); | |
CGContextSetInterpolationQuality(bitmap, quality); | |
// Draw into the context; this scales the image | |
CGContextDrawImage(bitmap, newRect, imageRef); | |
// Get the resized image from the context and a UIImage | |
CGImageRef newImageRef = CGBitmapContextCreateImage(bitmap); | |
UIImage *newImage = [UIImage imageWithCGImage:newImageRef]; | |
// Clean up | |
CGContextRelease(bitmap); | |
CGImageRelease(newImageRef); | |
return newImage; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment