Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I receiving an "invalid context" error in the following Core Graphics code?

I have the following drawing code:

    static int i=10;
    int x;
    int y;
    int x2;
    int y2;
    // Drawing code.
    CGContextRef c = UIGraphicsGetCurrentContext();    
    CGFloat colour[4] = {1.0f,0.0f,0.0f,1.0f};
    CGContextSetStrokeColor(c, colour);
    CGContextSetLineWidth(c, 1.0);
    CGContextBeginPath(c);
    NSLog(@"fired...");
    int xline[340] = {30,80,80,20};     
    int yline[340] = {40,40,20,20};
    CGContextBeginPath(c);
    CGContextMoveToPoint(c, x, y);
    CGContextAddLineToPoint(c,x2,y2);
    //CGContextStrokePath(c);    
    for (int j = 0; j <= 3; j++) {
        x2 = xline[j];
        y2 = yline[j];
        CGContextAddLineToPoint(c, x2, y2);
        x = x2;
        y = y2;
    }    
    CGContextStrokePath(c); 
    [self setNeedsDisplay];
    i++;

However, when it runs, I'm receiving the following errors:

Wed Aug 10 11:13:05 Mac-Minis-Mac-mini.local LineDraw[1880] <Error>: CGContextBeginPath: invalid context 0x0
Wed Aug 10 11:13:05 Mac-Minis-Mac-mini.local LineDraw[1880] <Error>: CGContextMoveToPoint: invalid context 0x0
Wed Aug 10 11:13:05 Mac-Minis-Mac-mini.local LineDraw[1880] <Error>: CGContextAddLineToPoint: invalid context 0x0
Wed Aug 10 11:13:05 Mac-Minis-Mac-mini.local LineDraw[1880] <Error>: CGContextAddLineToPoint: invalid context 0x0
Wed Aug 10 11:13:05 Mac-Minis-Mac-mini.local LineDraw[1880] <Error>: CGContextAddLineToPoint: invalid context 0x0
Wed Aug 10 11:13:05 Mac-Minis-Mac-mini.local LineDraw[1880] <Error>: CGContextAddLineToPoint: invalid context 0x0
Wed Aug 10 11:13:05 Mac-Minis-Mac-mini.local LineDraw[1880] <Error>: CGContextAddLineToPoint: invalid context 0x0
Wed Aug 10 11:13:05 Mac-Minis-Mac-mini.local LineDraw[1880] <Error>: CGContextDrawPath: invalid context 0x0

What could cause these errors and how can I solve this problem?

like image 771
nagarjun Avatar asked Jan 19 '23 00:01

nagarjun


1 Answers

Unless you have this code in the drawRect: method of a UIView subclass or have specifically pushed a graphics context onto the stack (e.g. by using UIGraphicsBeginImageContext), UIGraphicsGetCurrentContext() will return NULL.

All the drawing functions require a graphics context.

like image 99
omz Avatar answered Feb 28 '23 08:02

omz