Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is an invalid context error?

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?

like image 741
Tattat Avatar asked Apr 03 '10 09:04

Tattat


1 Answers

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

like image 59
Thomas Joulin Avatar answered Sep 22 '22 00:09

Thomas Joulin