Skip to content

Instantly share code, notes, and snippets.

@C4Tutorials
Last active December 16, 2015 09:58
Show Gist options
  • Save C4Tutorials/5416238 to your computer and use it in GitHub Desktop.
Save C4Tutorials/5416238 to your computer and use it in GitHub Desktop.
Exporting Tutorial, the CG way
//
// C4WorkSpace.m
// Exporting Tutorial
//
// Created by Travis Kirton.
//
#import "C4WorkSpace.h"
@implementation C4WorkSpace {
CGSize outputSize;
CGContextRef imageContext;
void *imageBuffer;
size_t bitsPerComponent;
size_t bitsPerPixel;
size_t componentsPerPixel;
size_t bytesPerRow;
}
-(void)setup {
C4Font *font = [C4Font fontWithName:@"AvenirNextCondensed-Heavy" size:172];
C4Shape *s = [C4Shape shapeFromString:@"DRAWING" withFont:font];
s.backgroundColor = C4RED;
s.center = self.canvas.center;
[self.canvas addShape:s];
imageContext = [self createImageContext];
NSString *fileName = @"exportedImageFromC4.png";
[self.canvas renderInContext:imageContext];
[self saveImage:fileName];
}
-(CGContextRef)createImageContext {
outputSize = self.canvas.frame.size;
componentsPerPixel = 4;
bytesPerRow = (size_t)outputSize.width * componentsPerPixel;
bitsPerComponent = 8;
bitsPerPixel = bitsPerComponent * componentsPerPixel;
imageBuffer = malloc((size_t)outputSize.height * bytesPerRow);
CGContextRef context = CGBitmapContextCreate(imageBuffer,
(size_t)outputSize.width,
(size_t)outputSize.height,
bitsPerComponent,
bytesPerRow,
CGColorSpaceCreateDeviceRGB(),
kCGImageAlphaPremultipliedFirst);
CGAffineTransform invert = CGAffineTransformMake(1, 0, 0, -1, 0, outputSize.height);
CGContextConcatCTM(context, invert);
return context;
}
-(void)saveImage:(NSString *)fileName {
CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL,
imageBuffer,
bytesPerRow * (size_t)outputSize.height,
NULL);
CGImageRef imageRef = CGImageCreate((size_t)outputSize.width,
(size_t)outputSize.height,
bitsPerComponent,
bitsPerPixel,
bytesPerRow,
CGColorSpaceCreateDeviceRGB(),
kCGImageAlphaPremultipliedFirst,
dataProvider,
NULL,
NO,
kCGRenderingIntentDefault);
UIImage *image = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
NSData *imageData = UIImagePNGRepresentation(image);
image = nil;
NSString *savePath = [[self documentsDirectory] stringByAppendingPathComponent:fileName];
[imageData writeToFile:savePath atomically:YES];
}
-(NSString *)documentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return paths[0];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment