Skip to content

Instantly share code, notes, and snippets.

@cntrump
Created November 9, 2020 09:05
Show Gist options
  • Save cntrump/f9da1db4a514f13f6e93359691e90013 to your computer and use it in GitHub Desktop.
Save cntrump/f9da1db4a514f13f6e93359691e90013 to your computer and use it in GitHub Desktop.
UIImage Extensions
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIImage (Extension)
+ (instancetype)imageWithSize:(CGSize)size drawingHandler:(BOOL (^)(CGRect bounds))handler;
+ (instancetype)imageWithColor:(UIColor *)color;
@end
NS_ASSUME_NONNULL_END
#import "UIImage+Extension.h"
@implementation UIImage (Extension)
+ (instancetype)imageWithSize:(CGSize)size drawingHandler:(BOOL (^)(CGRect bounds))handler {
if (size.width <= 0 || size.height <= 0 || !handler) {
return nil;
}
UIImage *image = nil;
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
if (context) {
CGRect bounds = CGContextGetClipBoundingBox(context);
if (handler(bounds)) {
image = UIGraphicsGetImageFromCurrentImageContext();
}
}
UIGraphicsEndImageContext();
return image;
}
+ (instancetype)imageWithColor:(UIColor *)color {
if (!color) {
return nil;
}
return [self imageWithSize:CGSizeMake(1, 1) drawingHandler:^BOOL(CGRect bounds) {
[color setFill];
UIRectFill(bounds);
return YES;
}];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment