Trying to create a UIimage from a Draw Context.
Not seeing anything. Am i missing something, or completely out my mind?
Code
- (UIImage *)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(context, 100, 100);
CGContextAddLineToPoint(context, 150, 150);
CGContextAddLineToPoint(context, 100, 200);
CGContextAddLineToPoint(context, 50, 150);
CGContextAddLineToPoint(context, 100, 100);
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
CGContextFillPath(context);
// Do your stuff here
CGImageRef imgRef = CGBitmapContextCreateImage(context);
UIImage* img = [UIImage imageWithCGImage:imgRef];
CGImageRelease(imgRef);
CGContextRelease(context);
return img;
}
I’m assuming this is not a
-drawRect:method on a view, because the return value is wrong. (-[UIView drawRect:]returnsvoid, not aUIImage*.)If it is on an NSView, that means you must be calling it directly, to get the return value. But that means that UIKit hasn’t set up a graphics context, the way it normally does before it calls
-drawRect:on the views in a window.Therefore, you shouldn’t assume that
UIGraphicsGetCurrentContext()is valid. It’s probably nil (have you checked?).If you just want an image: use
UIGraphicsBeginImageContext()to create a context, thenUIGraphicsGetImageFromCurrentImageContext()to extract aUIImage(no need for the intermediaryCGImage), thenUIGraphicsEndImageContext()to clean up.If you’re trying to capture an image of what your view drew: fix your
-drawRect:to return void, and find some other way to get that UIImage out of the view — either stash it in an ivar, or send it to some other object, or write it to a file, whatever you like.Also (less importantly):
Don’t
CGContextRelease(context). You didn’t create, copy, or retain it, so you shouldn’t release it.No need for the last
CGContextAddLineToPoint().CGContextFillPathwill implicitly close the path for you.