views:

87

answers:

2

I have a little sketch program that I've managed to throw together using Quartz2D, but I'm very new to the iOS platform and I'm having trouble figuring out how to allow the user to save their sketch. I have a CGContextRef that contains the sketch, how can I save it so that it can later be retrieved? Once it's saved, how can I retrieve it?

Thanks so much in advance for your help! I'm going to continue reading up on this now...

+2  A: 

There are different types of CGContexts. You are most likely having a screen based context, but you would need either a bitmapContext or a pdfContext, to create a bitmap or a pdf file.

See the UIKit Functions Reference. Functions that should be of interest are:

  • UIGraphicsBeginImageContext()
  • UIGraphicsGetImageFromCurrentImageContext()
  • UIGraphicsEndImageContext()
  • UIImageJPEGRepresentation()
  • UIImageWriteToSavedPhotosAlbum()
  • UIGraphicsBeginPDFContextToFile()
  • UIGraphicsEndPDFContext()
tonklon
+1  A: 

Here's how I did it...

Saving

CGImageRef imageRef = CGBitmapContextCreateImage(bitmapContext);
UIImage* image = [[UIImage alloc] initWithCGImage:imageRef];
NSData* imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:filePath atomically:YES];

Retrieving

UIImage* image = [UIImage imageWithContentsOfFile:filePath];
CGImageRef imageRef = [image CGImage];
BeachRunnerJoe
-1 The code leaks imageRef and image.
tc.
i didn't include the release statements, but they're in there.
BeachRunnerJoe
+1 Code snippits don't leak memory
Tim Rupe