Getting Error: CGContext Invalid When tying to Draw Circle

Discussion in 'iOS Programming' started by mandude, Mar 26, 2011.

  1. mandude macrumors member

    Joined:
    Nov 19, 2009
    #1
    I just updated to xcode 4 and I'm already having trouble simply drawing a small circle wherever the screen is tapped. I keep getting an invalid context error and I'm stumped. Any help is appreciated!

    Code:
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    
        UITouch *touch = [touches anyObject];
        CGPoint point1 = [touch locationInView:self.view]; 
        [self.view setNeedsDisplay];
        
        CGContextRef context = UIGraphicsGetCurrentContext();
    
    
        CGRect theRect = CGRectMake(point1.x, point1.y, 50, 50);
        CGContextFillEllipseInRect(context, theRect);
          CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
        CGContextDrawPath(context, kCGPathFillStroke);
    }
    
     
  2. kainjow Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #2
    You cannot draw in that method. You can only draw in the drawRect: method of the view.

    So make your point1 an instance variable, and then move the drawing/context code into the drawRect: method.
     
  3. mandude thread starter macrumors member

    Joined:
    Nov 19, 2009
    #3
    thanks for the help. Ive changed the code and I'm not getting any more invalid context errors but still, nothing occurs when i click on the view in the simulator. Here's the code now:

    Code:
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
        UITouch *touch = [touches anyObject];
        point1 = [touch locationInView:self.view]; 
        [self.view setNeedsDisplay];
    
    }
    
    -(void)drawRect:(CGRect) rect {
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        
        CGRect theRect = CGRectMake(point1.x, point1.y, 50, 50);
        CGContextAddEllipseInRect(context, theRect);
        CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
        CGContextDrawPath(context, kCGPathFillStroke);
    }
    
     

Share This Page