views:

186

answers:

2

I have drawn into a CGContext of a UIView.

- (void)drawRect:(CGRect)rect { 
    [self drawInContext:UIGraphicsGetCurrentContext()]  
}

I would like to save what I have drawn to a png file.

Is there a simple solution?

EDIT: Based on suggestions below - here's what I have so far....

-(void)createImage {
    NSString* outFile = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/image.png"];
    DLog(@"creating image file at %@", outFile);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
    NSData *imageData = UIImagePNGRepresentation(image);
    [imageData writeToFile:outFile 
                atomically:NO];
}

- (void)drawRect:(CGRect)rect { 
    [self drawInContext:UIGraphicsGetCurrentContext()]; 
    [self createImage];
}
+1  A: 

Call UIGraphicsGetImageFromCurrentImageContext to get an UIImage.
Then call UIImagePNGRepresentation to get an NSData of the UIImage encoded in PNG.
Finally, call -writeToFile:… to save the NSData.

KennyTM
+1  A: 
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:@"image.png"];
macatomy
I must be missing something simple. I do this within the drawRect call. Running on the iPhone simulator - i don't see any file created.
sylvanaar
You may have to specify the complete path to the Documents directory instead of just image.png.
macatomy
I updated my example code above - but no file is created in the emulator. Thanks for the help though.
sylvanaar