ibremn
2015-09-21 16:03:18 +08:00
+ (UIImage *)imageWithEmoji:(NSString *)emoji size:(CGFloat )size {
if (emoji.length == 0 ) return nil;
if (size < 1 ) return nil;
CGFloat scale = [UIScreen mainScreen].scale;
CTFontRef font = CTFontCreateWithName (CFSTR ("AppleColorEmoji"), size * scale, NULL );
if (!font ) return nil;
NSAttributedString *str = [[NSAttributedString alloc] initWithString:emoji attributes:@{ (__bridge id )kCTFontAttributeName:(__bridge id )font, (__bridge id )kCTForegroundColorAttributeName:(__bridge id )[UIColor clearColor].CGColor }];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB ();
CGContextRef ctx = CGBitmapContextCreate (NULL, size * scale, size * scale, 8, 0, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst );
CGContextSetInterpolationQuality (ctx, kCGInterpolationHigh );
CTLineRef line = CTLineCreateWithAttributedString ((__bridge CFTypeRef )str );
CGRect bounds = CTLineGetBoundsWithOptions (line, kCTLineBoundsUseGlyphPathBounds );
CGContextSetTextPosition (ctx, 0, -bounds.origin.y );
CTLineDraw (line, ctx );
CGImageRef imageRef = CGBitmapContextCreateImage (ctx );
UIImage *image = [[UIImage alloc] initWithCGImage:imageRef scale:scale orientation:UIImageOrientationUp];
CFRelease (font );
CGColorSpaceRelease (colorSpace );
CGContextRelease (ctx );
if (line )CFRelease (line );
if (imageRef ) CFRelease (imageRef );
return image;
}
加个 Category 到 UIImage 上,随时能把 Emoji 转为 Image ,性能不比直接读取图片差多少。。
UIImage *image = [UIImage imageWithEmoji:@"😄" size:80];