2424
2525#import " UIImageView+Letters.h"
2626
27+ @interface UIImageView (LettersPrivate)
28+
29+ - (UIImage *)imageSnapshotFromText : (NSString *)text backgroundColor : (UIColor *)color circular : (BOOL )isCircular ;
30+
31+ @end
32+
2733@implementation UIImageView (Letters)
2834
2935- (void )setImageWithString : (NSString *)string {
30- [self setImageWithString: string color: nil ];
36+ [self setImageWithString: string color: nil circular: NO ];
3137}
3238
3339- (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 {
3444 NSMutableString *displayString = [NSMutableString stringWithString: @" " ];
3545
3646 NSMutableArray *words = [[string componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet ]] mutableCopy ];
@@ -60,7 +70,7 @@ - (void)setImageWithString:(NSString *)string color:(UIColor *)color {
6070
6171 UIColor *backgroundColor = color ? color : [self randomColor ];
6272
63- self.image = [self imageSnapshotFromText: [displayString uppercaseString ] backgroundColor: backgroundColor];
73+ self.image = [self imageSnapshotFromText: [displayString uppercaseString ] backgroundColor: backgroundColor circular: isCircular ];
6474}
6575
6676#pragma mark - Helpers
@@ -89,7 +99,7 @@ - (UIColor *)randomColor {
8999 return [UIColor colorWithRed: red green: green blue: blue alpha: 1 .0f ];
90100}
91101
92- - (UIImage *)imageSnapshotFromText : (NSString *)text backgroundColor : (UIColor *)color {
102+ - (UIImage *)imageSnapshotFromText : (NSString *)text backgroundColor : (UIColor *)color circular : ( BOOL ) isCircular {
93103
94104 CGFloat scale = [UIScreen mainScreen ].scale ;
95105
@@ -107,6 +117,15 @@ - (UIImage *)imageSnapshotFromText:(NSString *)text backgroundColor:(UIColor *)c
107117
108118 CGContextRef context = UIGraphicsGetCurrentContext ();
109119
120+ if (isCircular) {
121+ //
122+ // Clip context to a circle
123+ //
124+ CGPathRef path = CGPathCreateWithEllipseInRect (self.bounds , NULL );
125+ CGContextAddPath (context, path);
126+ CGContextClip (context);
127+ }
128+
110129 //
111130 // Fill background of context
112131 //
0 commit comments