I am using CorePlot to draw different graphs in my application. Then, I would like to save this graph to a jpg file and publish to some social networking site (e.g., Twitter).
I did some documentation reading and understood that the following methods could be useful for me:
-
CGBitmapContextCreateImage: creating a CGImage as a copy from a bitmap graphics context (i.e., the view where my graph is situated or the whole screen – have I understood right?)
-
CGImageCreateWithImageInRect: I can clip out some part of the image if needed
-
[UIImage imageWithCGImage]: converting CGImage to an UIImage object
-
UIImageJPEGRepresentation: converting my UIImage object to a jpg NSData object which then I can share to my social network
-
The first question is: have I understood right the sequence of operations I have to carry out to accomplish my task? I would have tried it out myself, but I’ve got a problem which leads to the second question:
-
From where do I get the graphics context info to pass into CGBitmapContextCreateImage if I am using CorePlot? Sorry if it’s a dumb question, but I am not really at home with graphics contexts.
-
Thanks a lot for any help in advance! And if I get with all this somewhere I promise to post my code sample here.
Well, thanks to Brad, it was really easy, but as I promissed, I have to post the lines:
CPXYGraph *graph=[[CPXYGraph alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
// setting up the graph
// ...
UIImage *newImage=[graph imageOfLayer];
NSData *newPNG=UIImagePNGRepresentation(newImage); // or you can use JPG or PDF
// For test purposes I write the file to the Documents directory, but you can do whatever you want with your new .png file
NSString *filePath=[NSString stringWithFormat:@"%@/graph.png", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
if([newPNG writeToFile:filePath atomically:YES])
NSLog(@"Created new file successfully");
Actually, the CPLayer base class used for all drawing elements in Core Plot has a category method called
-imageOfLayerthat returns a UIImage instance of whatever layer you call it on. See theCPPlatformSpecificCategories.handCPPlatformSpecificCategories.mfiles in the framework if you want to see how this is accomplished.Simply use
-imageOfLayeron your CPGraph instance and then useUIImageJPEGRepresentation()to create the JPEG version of that image. You can then upload that image using the normal means.Likewise, there is a
-dataForPDFRepresentationOfLayermethod that returns an NSData instance containing a PDF representation of the layer and its sublayers.