Skip to content

Instantly share code, notes, and snippets.

@timothyekl
Created April 12, 2016 01:31
Show Gist options
  • Save timothyekl/31158dfe370fb7170ec073d90d6c25ac to your computer and use it in GitHub Desktop.
Save timothyekl/31158dfe370fb7170ec073d90d6c25ac to your computer and use it in GitHub Desktop.
UIImage(NFExtensions), a category for rescaling UIImage instances to generate thumbnails. Originally distributed as part of the UW PCE iOS course; now available under the MIT License.
// Copyright Tim Ekl 2014–2016. Available under MIT License.
#import <UIKit/UIKit.h>
@interface UIImage (NFExtensions)
- (UIImage *)scaledImageConstrainedToSize:(CGSize)size;
@end
// Copyright Tim Ekl 2014–2016. Available under MIT License.
#import "UIImage+NFExtensions.h"
@implementation UIImage (NFExtensions)
- (UIImage *)scaledImageConstrainedToSize:(CGSize)maximumSize;
{
return [self scaledImageConstrainedToSize:maximumSize contentScale:[[UIScreen mainScreen] scale]];
}
- (UIImage *)scaledImageConstrainedToSize:(CGSize)maximumSize contentScale:(CGFloat)contentScale;
{
#if 1 && defined(DEBUG)
// Leave a giant delay in Debug builds to stress the importance of threading this method
sleep(2);
#endif
CGSize currentSize = [self size];
CGFloat scaleFactor = MIN(maximumSize.width / currentSize.width, maximumSize.height / currentSize.height) * contentScale;
CGSize desiredSize = CGSizeApplyAffineTransform(currentSize, CGAffineTransformMakeScale(scaleFactor, scaleFactor));
UIGraphicsBeginImageContext(desiredSize);
[self drawInRect:CGRectIntegral((CGRect){.size = desiredSize, .origin = CGPointZero})];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return [[UIImage alloc] initWithCGImage:[scaledImage CGImage] scale:contentScale orientation:[scaledImage imageOrientation]];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment