Last active
April 13, 2018 13:01
-
-
Save kgn/5986379 to your computer and use it in GitHub Desktop.
A UIImage category class method for drawing icon font ligatures to images
This file contains hidden or 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
+ (UIImage *)iconWithFont:(UIFont *)font named:(NSString *)iconNamed forSize:(CGFloat)fontSize{ | |
static NSCache *cache = nil; | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
cache = [[NSCache alloc] init]; | |
}); | |
NSString *identifier = [NSString stringWithFormat:@"%@%@%f", font.fontName, iconNamed, fontSize]; | |
UIImage *image = [cache objectForKey:identifier]; | |
if(image == nil){ | |
NSMutableAttributedString *ligature = [[NSMutableAttributedString alloc] initWithString:iconNamed]; | |
[ligature setAttributes:@{(NSString *)kCTLigatureAttributeName:@(2), | |
(NSString *)kCTFontAttributeName:font} range:NSMakeRange(0, [ligature length])]; | |
CGSize iconSize = [ligature size]; | |
iconSize.width = ceil(iconSize.width); | |
iconSize.height = ceil(iconSize.height); | |
if(!CGSizeEqualToSize(CGSizeZero, iconSize)){ | |
UIGraphicsBeginImageContextWithOptions(iconSize, NO, 0); | |
[[UIColor blackColor] setFill]; | |
[ligature drawAtPoint:CGPointZero]; | |
image = UIGraphicsGetImageFromCurrentImageContext(); | |
UIGraphicsEndImageContext(); | |
[cache setObject:image forKey:identifier]; | |
} | |
} | |
return image; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment