Skip to content

Instantly share code, notes, and snippets.

@kgn
Last active April 13, 2018 13:01
Show Gist options
  • Save kgn/5986379 to your computer and use it in GitHub Desktop.
Save kgn/5986379 to your computer and use it in GitHub Desktop.
A UIImage category class method for drawing icon font ligatures to images
+ (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