Franky
Franky

Reputation: 1153

CGContext Ref as UIImage

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;
}

Upvotes: 0

Views: 2586

Answers (1)

Kurt Revis
Kurt Revis

Reputation: 27984

I'm assuming this is not a -drawRect: method on a view, because the return value is wrong. (-[UIView drawRect:] returns void, not a UIImage*.)

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, then UIGraphicsGetImageFromCurrentImageContext() to extract a UIImage (no need for the intermediary CGImage), then UIGraphicsEndImageContext() 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):

  1. Don't CGContextRelease(context). You didn't create, copy, or retain it, so you shouldn't release it.

  2. No need for the last CGContextAddLineToPoint(). CGContextFillPath will implicitly close the path for you.

Upvotes: 1

Related Questions