Skip to content

Instantly share code, notes, and snippets.

@depthlove
Forked from tomasbasham/UIImage+Scale.m
Created December 19, 2017 05:22
Show Gist options
  • Save depthlove/689fe277a1ab6e16d11a66226d6063bd to your computer and use it in GitHub Desktop.
Save depthlove/689fe277a1ab6e16d11a66226d6063bd to your computer and use it in GitHub Desktop.
Scale a UIImage to any given rect keeping the aspect ratio
@implementation UIImage (scale)
/**
* Scales an image to fit within a bounds with a size governed by
* the passed size. Also keeps the aspect ratio.
*
* Switch MIN to MAX for aspect fill instead of fit.
*
* @param newSize the size of the bounds the image must fit within.
* @return a new scaled image.
*/
- (UIImage *)scaleImageToSize:(CGSize)newSize {
CGRect scaledImageRect = CGRectZero;
CGFloat aspectWidth = newSize.width / self.size.width;
CGFloat aspectHeight = newSize.height / self.size.height;
CGFloat aspectRatio = MIN ( aspectWidth, aspectHeight );
scaledImageRect.size.width = self.size.width * aspectRatio;
scaledImageRect.size.height = self.size.height * aspectRatio;
scaledImageRect.origin.x = (newSize.width - scaledImageRect.size.width) / 2.0f;
scaledImageRect.origin.y = (newSize.height - scaledImageRect.size.height) / 2.0f;
UIGraphicsBeginImageContextWithOptions( newSize, NO, 0 );
[self drawInRect:scaledImageRect];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment