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);
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

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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