I want to make an image like this programmatically:
I have the upper image and text with me. Should I write text on the image?
I want to make it a complete .png image(image + label) and set it as the background of the button.
Draw text inside an image and return the resulting image:
+(UIImage*) drawText:(NSString*) text inImage:(UIImage*) image atPoint:(CGPoint) point { UIFont *font = [UIFont boldSystemFontOfSize:12]; UIGraphicsBeginImageContext(image.size); [image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)]; CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height); [[UIColor whiteColor] set]; [text drawInRect:CGRectIntegral(rect) withFont:font]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; }
Usage:
// note: replace "ImageUtils" with the class where you pasted the method above UIImage *img = [ImageUtils drawText:@"Some text" inImage:img atPoint:CGPointMake(0, 0)];
Change the origin of the text inside the image from 0,0 to whatever point you like.
To paint a rectangle of solid color behind the text, add the following before the line [[UIColor whiteColor] set];
:
[[UIColor brownColor] set]; CGContextFillRect(UIGraphicsGetCurrentContext(), CGRectMake(0, (image.size.height-[text sizeWithFont:font].height), image.size.width, image.size.height));
I'm using the text size to calculate the origin for the solid color rectangle, but you can replace it with any number.
My contribution to the first answer with iOS 7 support :
+(UIImage*) drawText:(NSString*) text inImage:(UIImage*) image atPoint:(CGPoint) point { UIGraphicsBeginImageContextWithOptions(image.size, YES, 0.0f); [image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)]; CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height); [[UIColor whiteColor] set]; UIFont *font = [UIFont boldSystemFontOfSize:12]; if([text respondsToSelector:@selector(drawInRect:withAttributes:)]) { //iOS 7 NSDictionary *att = @{NSFontAttributeName:font}; [text drawInRect:rect withAttributes:att]; } else { //legacy support [text drawInRect:CGRectIntegral(rect) withFont:font]; } UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; }
Hope this helps
EDIT: modified the UIGraphicsBeginImageContextWithOptions
to handle screen scale. Thk @SoftDesigner
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With