Created
March 6, 2012 02:37
-
-
Save ryanmaxwell/1983009 to your computer and use it in GitHub Desktop.
UIImage Resizing Utility Methods
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
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)size { | |
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { | |
UIGraphicsBeginImageContextWithOptions(size, NO, [[UIScreen mainScreen] scale]); | |
} else { | |
UIGraphicsBeginImageContext(size); | |
} | |
[image drawInRect:CGRectMake(0, 0, size.width, size.height)]; | |
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); | |
UIGraphicsEndImageContext(); | |
return newImage; | |
} | |
+ (UIImage *)imageWithImage:(UIImage *)image scaledToMaxWidth:(CGFloat)width maxHeight:(CGFloat)height { | |
CGFloat oldWidth = image.size.width; | |
CGFloat oldHeight = image.size.height; | |
CGFloat scaleFactor; | |
if (oldWidth > oldHeight) { | |
scaleFactor = width / oldWidth; | |
} else { | |
scaleFactor = height / oldHeight; | |
} | |
CGFloat newHeight = oldHeight * scaleFactor; | |
CGFloat newWidth = oldWidth * scaleFactor; | |
CGSize newSize = CGSizeMake(newWidth, newHeight); | |
return [self imageWithImage:image scaledToSize:newSize]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment