|
24 | 24 |
|
25 | 25 | #import "UIImageView+Letters.h" |
26 | 26 |
|
| 27 | +@interface UIImageView (LettersPrivate) |
| 28 | + |
| 29 | +- (UIImage *)imageSnapshotFromText:(NSString *)text backgroundColor:(UIColor *)color circular:(BOOL)isCircular; |
| 30 | + |
| 31 | +@end |
| 32 | + |
27 | 33 | @implementation UIImageView (Letters) |
28 | 34 |
|
29 | 35 | - (void)setImageWithString:(NSString *)string { |
30 | | - [self setImageWithString:string color:nil]; |
| 36 | + [self setImageWithString:string color:nil circular:NO]; |
31 | 37 | } |
32 | 38 |
|
33 | 39 | - (void)setImageWithString:(NSString *)string color:(UIColor *)color { |
| 40 | + [self setImageWithString:string color:color circular:NO]; |
| 41 | +} |
| 42 | + |
| 43 | +- (void)setImageWithString:(NSString *)string color:(UIColor *)color circular:(BOOL)isCircular { |
34 | 44 | NSMutableString *displayString = [NSMutableString stringWithString:@""]; |
35 | 45 |
|
36 | 46 | NSMutableArray *words = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] mutableCopy]; |
@@ -60,7 +70,7 @@ - (void)setImageWithString:(NSString *)string color:(UIColor *)color { |
60 | 70 |
|
61 | 71 | UIColor *backgroundColor = color ? color : [self randomColor]; |
62 | 72 |
|
63 | | - self.image = [self imageSnapshotFromText:[displayString uppercaseString] backgroundColor:backgroundColor]; |
| 73 | + self.image = [self imageSnapshotFromText:[displayString uppercaseString] backgroundColor:backgroundColor circular:isCircular]; |
64 | 74 | } |
65 | 75 |
|
66 | 76 | #pragma mark - Helpers |
@@ -89,7 +99,7 @@ - (UIColor *)randomColor { |
89 | 99 | return [UIColor colorWithRed:red green:green blue:blue alpha:1.0f]; |
90 | 100 | } |
91 | 101 |
|
92 | | -- (UIImage *)imageSnapshotFromText:(NSString *)text backgroundColor:(UIColor *)color { |
| 102 | +- (UIImage *)imageSnapshotFromText:(NSString *)text backgroundColor:(UIColor *)color circular:(BOOL)isCircular { |
93 | 103 |
|
94 | 104 | CGFloat scale = [UIScreen mainScreen].scale; |
95 | 105 |
|
@@ -121,6 +131,15 @@ - (UIImage *)imageSnapshotFromText:(NSString *)text backgroundColor:(UIColor *)c |
121 | 131 | [text drawInRect:CGRectMake(bounds.size.width/2 - textSize.width/2, bounds.size.height/2 - textSize.height/2, textSize.width, textSize.height) |
122 | 132 | withAttributes:@{NSFontAttributeName:[self fontForText], NSForegroundColorAttributeName:[UIColor whiteColor]}]; |
123 | 133 |
|
| 134 | + if (isCircular) { |
| 135 | + // |
| 136 | + // Clip context to a circle |
| 137 | + // |
| 138 | + CGPathRef path = CGPathCreateWithEllipseInRect(self.bounds, NULL); |
| 139 | + CGContextAddPath(context, path); |
| 140 | + CGContextClip(context); |
| 141 | + } |
| 142 | + |
124 | 143 | UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext(); |
125 | 144 | UIGraphicsEndImageContext(); |
126 | 145 |
|
|
0 commit comments