Skip to content

Instantly share code, notes, and snippets.

@ka2n
Created May 18, 2012 14:36
Show Gist options
  • Save ka2n/2725570 to your computer and use it in GitHub Desktop.
Save ka2n/2725570 to your computer and use it in GitHub Desktop.
saveNSStringAsImg
- (void)saveMessageAsImg: (NSString *)comment fileName:(NSString *) filePath
{
UIFont *font = [UIFont fontWithName:@"HiraKakuProN-W3" size:60];
CGSize size = [comment sizeWithFont: font];
UIGraphicsBeginImageContextWithOptions(CGSizeMake(size.width, size.height), NO, [[UIScreen mainScreen] scale]);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextSetFillColorSpace(ctx, colorSpace);
CGColorSpaceRelease(colorSpace);
CGContextSetAllowsAntialiasing(ctx, YES);
CGContextSetAllowsFontSmoothing(ctx, YES);
CGContextSetShouldAntialias(ctx, YES);
CGContextSetShouldSmoothFonts(ctx, YES);
CGContextSetRGBFillColor(ctx, 0.0, 0.0, 0.0, 1.0);
CGContextFillRect(ctx, CGRectMake(0.0, 0.0, size.width, size.height)); // Background
CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0);
[comment drawInRect:CGRectMake(0, 0, size.width, size.height) withFont:font];
CGImageRef imageRef = CGBitmapContextCreateImage(ctx);
UIImage *image = [UIImage imageWithCGImage:imageRef];
NSData *pngData = UIImagePNGRepresentation(image);
[pngData writeToFile:filePath atomically:NO];
CGImageRelease(imageRef);
LOG(@"save comment: %@", filePath);
UIGraphicsEndImageContext();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment