Skip to content

Instantly share code, notes, and snippets.

@jonahb
Created September 20, 2013 07:12
Show Gist options
  • Save jonahb/6634236 to your computer and use it in GitHub Desktop.
Save jonahb/6634236 to your computer and use it in GitHub Desktop.
#import <CoreGraphics/CoreGraphics.h>
@interface GraphicsNode(Protected)
- (void)requestDrawGraphics;
- (void)drawGraphics:(CGContextRef)context;
@end
#import "CCNode.h"
@interface GraphicsNode : CCNode
@end
#import "GraphicsNode.h"
#import "GraphicsNode+Protected.h"
#import "CoreGraphicsExtensions.h"
#import "cocos2d.h"
#define BITS_PER_COMPONENT 8
#define BYTES_PER_PIXEL 4
@interface GraphicsNode ()
@property (nonatomic, assign) CCSprite *sprite;
@property (nonatomic, assign) void *bitmap;
@property (nonatomic, assign) CGSize bitmapSize;
@end
@implementation GraphicsNode
- (void)dealloc {
if (_bitmap) {
free(_bitmap);
_bitmap = NULL;
}
[super dealloc];
}
- (void)setContentSize:(CGSize)contentSize {
[super setContentSize:contentSize];
[self createBitmap];
[self requestDrawGraphics];
}
#pragma mark Protected
- (void)drawGraphics:(CGContextRef)context {
assert(NO);
}
- (void)requestDrawGraphics {
NSLog(@"requestDrawGraphics");
if (self.sprite) {
[self removeChild:self.sprite cleanup:YES];
self.sprite = nil;
}
if (!self.bitmap)
return;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(self.bitmap,
self.bitmapSize.width,
self.bitmapSize.height,
BITS_PER_COMPONENT,
BYTES_PER_PIXEL * self.bitmapSize.width,
colorSpace,
kCGImageAlphaPremultipliedLast);
[self drawGraphics:context];
CGImageRef image = CGBitmapContextCreateImage(context);
CCTexture2D *texture = [[[CCTexture2D alloc] initWithCGImage:image resolutionType:kCCResolutioniPhoneRetinaDisplay] autorelease];
CCSprite *sprite = [CCSprite spriteWithTexture:texture];
CGImageRelease(image);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
self.sprite = sprite;
[self addChild:sprite];
}
#pragma mark Private
- (void)createBitmap {
if (_bitmap) {
free(_bitmap);
_bitmap = NULL;
}
self.bitmapSize = CGSizeScale(self.contentSize, CC_CONTENT_SCALE_FACTOR());
if (CGSizeArea(self.bitmapSize) > 0) {
if (!(_bitmap = malloc(CGSizeArea(self.bitmapSize) * BYTES_PER_PIXEL))) {
[NSException raise:NSGenericException format:@"Out of memory allocating GraphicsNode bitmap"];
}
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment