Created
October 18, 2012 21:59
-
-
Save veritech/3915021 to your computer and use it in GitHub Desktop.
UIImage + rendering blocks
This file contains hidden or 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
| #import <UIKit/UIKit.h> | |
| #import <QuartzCore/QuartzCore.h> | |
| typedef void(^UIImageRenderBlock)(CGContextRef context); | |
| @interface UIImage (render) | |
| +(UIImage *)imageWithSize:(CGSize) canvasSize block:(UIImageRenderBlock) aBlock; | |
| @end | |
| @implementation UIImage (render) | |
| +(UIImage *)imageWithSize:(CGSize) canvasSize block:(UIImageRenderBlock) aBlock { | |
| CGContextRef context; | |
| void *bitmapData; | |
| CGColorSpaceRef colorSpace; | |
| int bitmapByteCount; | |
| int bitmapBytesPerRow; | |
| CGImageRef resultImage; | |
| UIImage *image; | |
| // | |
| bitmapBytesPerRow = canvasSize.width * 4; | |
| bitmapByteCount = (bitmapBytesPerRow * canvasSize.height); | |
| //Create the color space | |
| colorSpace = CGColorSpaceCreateDeviceRGB(); | |
| bitmapData = malloc( bitmapByteCount ); | |
| //Check the the buffer is alloc'd | |
| if( bitmapData == NULL ){ | |
| NSLog(@"Buffer could not be alloc'd"); | |
| } | |
| //Create the context | |
| context = CGBitmapContextCreate(bitmapData, canvasSize.width, canvasSize.height, 8, bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast); | |
| if( context == NULL ){ | |
| NSLog(@"Context could not be created"); | |
| } | |
| //Render user data | |
| aBlock(context); | |
| //The contents of the context could be saved out as follows | |
| //Get the result image | |
| resultImage = CGBitmapContextCreateImage(context); | |
| //Save the image | |
| image = [UIImage imageWithCGImage:resultImage]; | |
| //Cleanup | |
| CGImageRelease(resultImage); | |
| free(bitmapData); | |
| CGColorSpaceRelease(colorSpace); | |
| return image; | |
| } | |
| @end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment