2

When the view loads in my iOS application, I dynamically create a UIImageView and place my Image inside of it. I would like to draw a simple circle on top of the UIImageView, but have been unable to do so thus far.

I wrote this code and attempted to draw a circle upon recieving an event from another object...

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 0, 0, 255, 0.5);
CGContextFillRect(context, CGRectMake(10, 10, 10, 10));

...but nothing happens I receive an error.

<Error>: CGContextSetRGBStrokeColor: invalid context 0x0
<Error>: CGContextFillRects: invalid context 0x0

I'm attempting to draw above everything, to no avail. What am I doing wrong?

1

1 Answer 1

4

attempted to draw a circle upon recieving an event from another object. [emphasis mine]

Your CGContextRef is NULL because there is no graphics context in the place that you are calling UIGraphicsGetCurrentContext.

When you're in the drawRect: of a view, a context has already been set up for you, so you can draw and can get the current context if you need to. In an arbitrary method (such as an IBAction) however, there may not be a graphics context for you to draw into. You need to either create one, using perhaps UIGraphicsBeginImageContextWithOptions, or (preferably) just set a flag in your event handler method to indicate that something extra should be drawn the next time through drawRect:, and then call setNeedsDisplay.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.