Create UIImage with text

While making an application, showing user’s image is a very common use case. Gone were the days when we used to show anonymous image in case a person’s profile image or display image is not present. We can easily show a person’s initials to make it easier to identify the person. Here’s a simple category to generate an UIImage with centered text overlayed on top of it.

@implementation UIImage (PGHelpers)
- (UIImage *)imageWithCenteredText:(NSString *)text withfont:(UIFont *)font {
    CGSize size = [text sizeWithAttributes:@{NSFontAttributeName : font}];
    return [self imageWithText:text atPoint:CGPointMake((self.size.width - size.width) / 2, (self.size.height - size.height) / 2) withFont:font];

}

- (UIImage *)imageWithText:(NSString *)text atPoint:(CGPoint)point withFont:(UIFont *)font {
    UIGraphicsBeginImageContextWithOptions(self.size, YES, 0.0f);
    [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)];
    CGRect rect = CGRectMake(point.x, point.y, self.size.width, self.size.height);
    [[UIColor whiteColor] set];

    NSDictionary *att = @{NSFontAttributeName : font, NSForegroundColorAttributeName : [UIColor whiteColor]};
    [text drawInRect:rect withAttributes:att];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}
@end

This can be chained with other methods (e.g. from UIImage-Additions, UIImage-ResizeMagick etc.) to create compelling profile images with advance blurring effects etc. Here’s an example that resizes the image to size x size, blurs it, adds the user initials in the center, crops it to a circle and finally adds a border around it:

UIImage *blurredImage = [[image resizedImageByMagick:[NSString stringWithFormat:@"%dx%d#", size * 3, size * 3]] blurredImageWithRadius:size / 8 iterations:3 tintColor:[UIColor clearColor]];
[[[blurredImage imageWithCenteredText:profile.avatarInitials withfont:[UIFont fontWithName:kPGFontNameAvenirNextCondensedRegular size:60]] add_imageWithRoundedBounds] borderedImageWithPadding:30];
Published 19 Dec 2015

I build mobile and web applications. Full Stack, Rails, React, Typescript, Kotlin, Swift
Pulkit Goyal on Twitter