Creating an UIImage with given text and size

static UIImage *createImageWithText(CGSize imageSize, NSString *text) {

// Create a bitmap graphics context of the given size
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, imageSize.width, imageSize.height, 8, imageSize.width*4, colorSpace, kCGImageAlphaPremultipliedLast);
if (context== NULL) {
return nil;

// Custom CGContext coordinate system is flipped with respect to UIView, so transform, then push
CGContextScaleCTM(context, 1.0, -1.0);

// Inset the text rect then draw the text
CGRect textRect = CGRectMake(4, 2, imageSize.width - 8, imageSize.height - 8);
UIFont *font = [UIFont boldSystemFontOfSize:24];
[[UIColor whiteColor] set];
[text drawInRect:textRect withFont:font
lineBreakMode:UILineBreakModeTailTruncation alignment:UITextAlignmentCenter];

// Create and return the UIImage object
CGImageRef cgImage = CGBitmapContextCreateImage(context);
UIImage *uiImage = [[UIImage alloc] initWithCGImage:cgImage];
return uiImage;

Note: This is a repost of this


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s