Skip to content

Instantly share code, notes, and snippets.

@ryanmaxwell
Created March 6, 2012 02:37
Show Gist options
  • Save ryanmaxwell/1983009 to your computer and use it in GitHub Desktop.
Save ryanmaxwell/1983009 to your computer and use it in GitHub Desktop.
UIImage Resizing Utility Methods
+ (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