Last active
August 29, 2015 14:26
-
-
Save maximbilan/b7cbd88f4ddac52eec59 to your computer and use it in GitHub Desktop.
UIImage from text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+ (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