Skip to content

Instantly share code, notes, and snippets.

@ccgus
Created July 16, 2012 18:57
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 ccgus/3124346 to your computer and use it in GitHub Desktop.
Save ccgus/3124346 to your computer and use it in GitHub Desktop.
Sketching up a little drawable context guy.
@interface FMDrawContext : NSObject {
CGContextRef _cgContext;
}
+ (id)drawContextWithSize:(NSSize)s;
- (CGImageRef)CGImage __attribute__((cf_returns_retained));
- (NSImage*)NSImage;
- (NSData*)dataOfType:(NSString*)uti;
- (void)drawInContextWithBlock:(void (^)())r;
- (CGContextRef)context;
@end
@implementation FMDrawContext
+ (id)drawContextWithSize:(NSSize)s {
CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
CGContextRef ctx = CGBitmapContextCreate(nil, s.width, s.height, 8, 0, cs, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host);
if (!ctx) {
return nil;
}
FMDrawContext *drawContext = [[FMDrawContext new] autorelease];
[drawContext setContext:ctx];
return drawContext;
}
- (void)dealloc {
if (_cgContext) {
CGContextRelease(_cgContext);
}
[super dealloc];
}
- (CGImageRef)CGImage {
return CGBitmapContextCreateImage(_cgContext);
}
- (NSImage*)NSImage {
CGImageRef cimg = [self CGImage];
NSImage *nimg = [NSImage imageWithCGImage:cimg];
CGImageRelease(cimg);
return nimg;
}
- (NSData*)dataOfType:(NSString*)uti {
CGImageRef img = [self CGImage];
NSMutableData *data = [NSMutableData data];
CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((CFMutableDataRef)data, (CFStringRef)uti, 1, nil);
if (!imageDestination) {
CGImageRelease(img);
return nil;
}
CGImageDestinationAddImage(imageDestination, img, (CFDictionaryRef)[NSDictionary dictionary]);
CGImageDestinationFinalize(imageDestination);
CFRelease(imageDestination);
CGImageRelease(img);
return data;
}
- (CGContextRef)context {
return _cgContext;
}
- (void)setContext:(CGContextRef)ctx {
NSAssert(!_cgContext, @"There's already a draw context! This guy is meant to be one-shot.");
_cgContext = ctx;
}
- (void)drawInContextWithBlock:(void (^)())r {
NSGraphicsContext *currentNSContext = [NSGraphicsContext graphicsContextWithGraphicsPort:_cgContext flipped:NO];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:currentNSContext];
r();
[NSGraphicsContext restoreGraphicsState];
}
@end
@ccgus
Copy link
Author

ccgus commented Jul 16, 2012

Example for making a quick PNG:

FMDrawContext *dc = [FMDrawContext drawContextWithSize:[img size]];

[dc drawInContextWithBlock:^{
// do your drawing here.
}];

NSData *pngData = [dc dataOfType:(id)kUTTypePNG];

@ccgus
Copy link
Author

ccgus commented Jul 16, 2012

OH DEAR LORD I'M LEAKING THE COLORSPACE UGH

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment