Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

mandude

macrumors member
Original poster
Nov 19, 2009
64
0
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);
}
 
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.
 
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);
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.