Why is there an invalid context error?

Here is the code I use for drawing:

- (void) drawSomething { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetRGBStrokeColor(context, 1, 0, 0, 1); CGContextSetLineWidth(context, 6.0); CGContextMoveToPoint(context, 100.0f, 100.0f); CGContextAddLineToPoint(context, 200.0f, 200.0f); CGContextStrokePath(context); NSLog(@"draw"); } 

But I got an error:

 [Session started at 2010-04-03 17:51:07 +0800.] Sat Apr 3 17:51:09 MacBook.local MyApp[12869] <Error>: CGContextSetRGBStrokeColor: invalid context Sat Apr 3 17:51:09 MacBook.local MyApp[12869] <Error>: CGContextSetLineWidth: invalid context Sat Apr 3 17:51:09 MacBook.local MyApp[12869] <Error>: CGContextMoveToPoint: invalid context Sat Apr 3 17:51:09 MacBook.local MyApp[12869] <Error>: CGContextAddLineToPoint: invalid context Sat Apr 3 17:51:09 MacBook.local MyApp[12869] <Error>: CGContextDrawPath: invalid context 

Why does this prompt me to say that the context is invalid?

+7
objective-c iphone xcode quartz-graphics
source share
2 answers

As the documentation says:

The current graphics context is zero by default. Prior to calling the drawRect: method, viewers insert the actual context onto the stack, making it relevant.

So you need to put this code in the drawRect method

+12
source share

From my answer to this similar question :

If you need to draw it on the screen, you need to find the drawing code in the -drawRect: UIView (or –drawInContext: CALayer) method. To update its contents, you need to call -setNeedsDisplay in a UIView or CALayer. Attempting to draw at any other time will result in an "invalid context" error.

See also this question .

+8
source share

All Articles