Last active
February 1, 2024 19:04
-
-
Save tomasbasham/10533743 to your computer and use it in GitHub Desktop.
Scale a UIImage to any given rect keeping the aspect ratio
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
@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
Swift 5 (Mac Os)
This working for me but I'm sure if is the best approach