0

I draw an initial simple rect using UIBezierPath and fill it with color. How can I change only its color by touching on it?

- (void) drawRect:(CGRect)rect
{
    // Drawing code
    [self drawRectWithFrame:_myRect fillColor:_firstColor];
}
- (void) drawRectWithFrame:(CGRect)frame fillColor:(UIColor *)color
{
    [color setFill];
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:frame];
    [path fill];
}
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //get the rect color from touches (pixel color)     
    UIColor *color = [self getRectColorFromTouches:touches];

    //chnage the rect color
    if (color == _firstColor) {

    //doesn't work
    //[self drawRectWithFrame:_myRect fillColor:_secondColor]; //??
        //How can I do that?
    }
    else {
        //??
    }    
}
suyama
  • 262
  • 2
  • 15

1 Answers1

0

Some remarks :

  • Instead of overriding UIView touch event methods, you should use a UIGestureRecognizer. In your case, a UItapGestureRecognizer might be enough. (this way, it will be easier to handle conflict between different touch actions, that's the reason why gestureRecognizers were created!)

  • When you receive tap, change a local property of your view (for example, a BOOL isRectangleDrawn might be changed each time the view receives the tap)

  • Finally - and that's what missing in your code, that otherwise should be correct - don't forget to call [self setNeedsDisplay] to be sure your view's - (void) drawRect:(CGRect)rect method gets called

Vinzzz
  • 11,746
  • 5
  • 36
  • 42
  • It works. Thank you. But I get the following error: _italic_ **bold** `: CGContextRestoreGState: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.`. I've read abut this error: [link](http://stackoverflow.com/questions/19599266/invalid-context-0x0-under-ios-7-0-and-system-degradation) – suyama Apr 07 '14 at 16:23
  • I'm not sure about this one, altough I encountered the `UITextField` bug mentionned in your link. Try adding `UIGraphicsBeginImageContext` in `drawRect`, just before your `UIBezier` draw call... – Vinzzz Apr 08 '14 at 10:20
  • Yes.. Drawing in 'drawRect' was the solution. Thanks. – suyama Apr 27 '14 at 21:12