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);
CGColorSpaceRelease(colorSpace);
if (context== NULL) {
return nil;
}
// Custom CGContext coordinate system is flipped with respect to UIView, so transform, then push
CGContextTranslateCTM(context,0,imageSize.height);
CGContextScaleCTM(context, 1.0, -1.0);
UIGraphicsPushContext(context);
// 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];
UIGraphicsPopContext();
CGContextRelease(context);
CGImageRelease(cgImage);
return uiImage;
}
Note: This is a repost of this