Created
November 9, 2020 09:05
-
-
Save cntrump/f9da1db4a514f13f6e93359691e90013 to your computer and use it in GitHub Desktop.
UIImage Extensions
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
#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 |
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
#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