Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save younthu/fe774c0c040e940ec2f5 to your computer and use it in GitHub Desktop.
Save younthu/fe774c0c040e940ec2f5 to your computer and use it in GitHub Desktop.
#import <AppKit/AppKit.h>
@interface NSImage (DrawAttributedString)
+ (NSImage *)imageWithAttributedString:(NSAttributedString *)attributedString
backgroundColor:(NSColor *)backgroundColor;
+ (NSImage *)imageWithAttributedString:(NSAttributedString *)attributedString;
+ (NSImage *)imageWithString:(NSString *)string;
@end
#import "NSImage+DrawAttributedString.h"
@implementation NSImage (DrawAttributedString)
+ (NSImage *)imageWithAttributedString:(NSAttributedString *)attributedString
backgroundColor:(NSColor *)backgroundColor
{
NSSize boxSize = [attributedString size];
NSRect rect = NSMakeRect(0.0, 0.0, boxSize.width, boxSize.height);
NSImage *image = [[NSImage alloc] initWithSize:boxSize];
[image lockFocus];
[backgroundColor set];
NSRectFill(rect);
[attributedString drawInRect:rect];
[image unlockFocus];
return [image autorelease];
}
+ (NSImage *)imageWithAttributedString:(NSAttributedString *)attributedString
{
return [self imageWithAttributedString:attributedString
backgroundColor:[NSColor clearColor]];
}
+ (NSImage *)imageWithString:(NSString *)string
{
NSAttributedString *attrString = [[[NSAttributedString alloc] initWithString:string] autorelease];
return [self imageWithAttributedString:attrString];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment