Skip to content

Instantly share code, notes, and snippets.

@engmsaleh
Created November 13, 2015 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save engmsaleh/6fa1f2ac1e572631cde4 to your computer and use it in GitHub Desktop.
Save engmsaleh/6fa1f2ac1e572631cde4 to your computer and use it in GitHub Desktop.
Add Text on UIImage and return new UIImage
- (UIImage*)image:(UIImage*)image withText:(NSString*)text
{
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
[image drawInRect:rect];
/// Make a copy of the default paragraph style
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
/// Set line break mode
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
/// Set text horizontal alignment
paragraphStyle.alignment = NSTextAlignmentCenter;
NSDictionary *attributes = @{NSFontAttributeName : [UIFont boldSystemFontOfSize:16],
NSStrokeWidthAttributeName : @(4),
NSStrokeColorAttributeName : [UIColor whiteColor],
NSParagraphStyleAttributeName : paragraphStyle};
CGSize size = [text sizeWithAttributes:attributes];
CGRect newRect = CGRectMake(rect.origin.x,
rect.origin.y + (rect.size.height - size.height)/2.0,
rect.size.width,
size.height);
[text drawInRect:newRect withAttributes:attributes];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment