Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a UIImage from the current graphics context?

Tags:

I'd like to create a UIImage object from the current graphics context. More specifically, my use case is a view that the user can draw lines on. They may draw incrementally. After they are done, I'd like to create a UIImage to represent their drawing.

Here is what drawRect: looks like for me now:

- (void)drawRect:(CGRect)rect { CGContextRef c = UIGraphicsGetCurrentContext();  CGContextSaveGState(c); CGContextSetStrokeColorWithColor(c, [UIColor blackColor].CGColor); CGContextSetLineWidth(c,1.5f);  for(CFIndex i = 0; i < CFArrayGetCount(_pathArray); i++) {     CGPathRef path = CFArrayGetValueAtIndex(_pathArray, i);     CGContextAddPath(c, path); }  CGContextStrokePath(c);  CGContextRestoreGState(c); } 

... where _pathArray is of type CFArrayRef, and is populated every time touchesEnded: is invoked. Also note that drawRect: may be invoked several times, as the user draws.

When the user is done, I'd like to create a UIImage object that represents the graphics context. Any suggestions on how to do this?

like image 918
figelwump Avatar asked Jul 11 '09 04:07

figelwump


People also ask

How do you add a UIImage in Objective C?

UIImage *img = [[UIImage alloc] init]; [img setImage:[UIImage imageNamed:@"anyImageName"]];

What is a UIImage?

An object that manages image data in your app.

What is the difference between UIImage and UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .

What is Cgcontext?

A graphics context contains drawing parameters and all device-specific information needed to render the paint on a page to the destination, whether the destination is a window in an application, a bitmap image, a PDF document, or a printer.


1 Answers

You need to setup the graphics context first:

UIGraphicsBeginImageContext(myView.bounds.size); [myView.layer renderInContext:UIGraphicsGetCurrentContext()]; viewImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); 
like image 142
Kelvin Avatar answered Oct 14 '22 07:10

Kelvin