Skip to content

Instantly share code, notes, and snippets.

@maximbilan
Last active August 29, 2015 14:26
Show Gist options
  • Save maximbilan/b7cbd88f4ddac52eec59 to your computer and use it in GitHub Desktop.
Save maximbilan/b7cbd88f4ddac52eec59 to your computer and use it in GitHub Desktop.
UIImage from text
+ (UIImage *)imageFromText:(NSString *)text size:(CGSize)size fontName:(NSString *)fontName maxFontSize:(CGFloat)maxFontSize minFontSize:(CGFloat)minFontSize
{
UIFont *font;
CGSize fontSize;
for (CGFloat maxSize = maxFontSize; maxSize >= minFontSize; maxSize -= 1.f) {
font = [UIFont fontWithName:fontName size:maxSize];
fontSize = [text sizeWithAttributes:@{ NSFontAttributeName : font }];
if (fontSize.width <= size.width) {
break;
}
}
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
CGFloat fontPosX = (size.width - fontSize.width) * 0.5;
CGFloat fontPosY = (size.height - fontSize.height) * 0.5;
[text drawAtPoint:CGPointMake(fontPosX, fontPosY) withAttributes:@{ NSFontAttributeName : font }];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
[image drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(ctx, 0.0, 0.0, 0.0, 1.0);
CGContextStrokeRect(ctx, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment