views:

512

answers:

2

Here is the code I use to draw:

- (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 the error like this:

[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 it prompt me to say that the context is invalided?

+2  A: 

Like the documentation says :

The current graphics context is nil by default. Prior to calling its drawRect: method, view objects push a valid context onto the stack, making it current.

So you need to put this code in the drawRect method

Thomas Joulin
still don't get that
Tattat
The iPhone OS is build so that the graphic context (accessible to us via UIGraphicsGetCurrentContext()) is created only when needed. That's needed when you want to draw something, so in the drawRect: methode that you will override in your class.Even if you can call directly drawRect:, the iPhone SDK documentation advice you not to. So instead of just renaming your method drawSomething: to drawRect: and calling it, which would work, I'll advise you to do that but call setNeedsDisplay like @Brad Larson told you to ;)
Thomas Joulin
thz guys, u are very helpful.
Tattat
+2  A: 

From my answer to this similar question:

If this is to be drawn to the screen, you'll need to locate your drawing code within the -drawRect: method of a UIView (or –drawInContext: of a CALayer). To update its contents, you'd need to call -setNeedsDisplay on the UIView or CALayer. Attempting drawing at any other time will cause the "invalid context" error you're seeing.

See also this question.

Brad Larson