Skip to content

Commit d03df96

Browse files
committed
Added emoji support (Resolves #6)
1 parent 32de9b3 commit d03df96

2 files changed

Lines changed: 16 additions & 5 deletions

File tree

UIImageView+Letters/UIImageView+Letters.m

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,9 @@ - (void)setImageWithString:(NSString *)string color:(UIColor *)color circular:(B
5858
if ([words count]) {
5959
NSString *firstWord = [words firstObject];
6060
if ([firstWord length] != 0) {
61-
[displayString appendString:[firstWord substringToIndex:1]];
61+
// Get character range to handle emoji (emojis consist of 2 characters in sequence)
62+
NSRange firstLetterRange = [firstWord rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, 1)];
63+
[displayString appendString:[firstWord substringWithRange:firstLetterRange]];
6264
}
6365

6466
if ([words count] >= 2) {
@@ -70,7 +72,9 @@ - (void)setImageWithString:(NSString *)string color:(UIColor *)color circular:(B
7072
}
7173

7274
if ([words count] > 1) {
73-
[displayString appendString:[lastWord substringToIndex:1]];
75+
// Get character range to handle emoji (emojis consist of 2 characters in sequence)
76+
NSRange lastLetterRange = [lastWord rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, 1)];
77+
[displayString appendString:[lastWord substringWithRange:lastLetterRange]];
7478
}
7579
}
7680
}
@@ -151,10 +155,17 @@ - (UIImage *)imageSnapshotFromText:(NSString *)text backgroundColor:(UIColor *)c
151155
//
152156
// Draw text in the context
153157
//
154-
CGSize textSize = [text sizeWithAttributes:@{NSFontAttributeName:[self fontForText: fontName]}];
158+
CGSize textSize = [text sizeWithAttributes:@{NSFontAttributeName:[self fontForText:fontName]}];
155159
CGRect bounds = self.bounds;
156-
[text drawInRect:CGRectMake(bounds.size.width/2 - textSize.width/2, bounds.size.height/2 - textSize.height/2, textSize.width, textSize.height)
157-
withAttributes:@{NSFontAttributeName:[self fontForText:fontName], NSForegroundColorAttributeName:[UIColor whiteColor]}];
160+
161+
[text drawInRect:CGRectMake(bounds.size.width/2 - textSize.width/2,
162+
bounds.size.height/2 - textSize.height/2,
163+
textSize.width,
164+
textSize.height)
165+
withAttributes:@{
166+
NSFontAttributeName:[self fontForText:fontName],
167+
NSForegroundColorAttributeName:[UIColor whiteColor]
168+
}];
158169

159170
UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();
160171
UIGraphicsEndImageContext();

0 commit comments

Comments
 (0)