tags:

views:

67

answers:

1

i want to draw a line in the rect of UIView when i touch screen. please can someone help me to check the code ! thanks

- (void)drawRect:(CGRect)rect {
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 5.0);
CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor);
CGContextSetFillColorWithColor(context, [UIColor greenColor].CGColor);
CGContextMoveToPoint(context, 100.0, 30.0);
CGContextAddLineToPoint(context, 200.0, 30.0);
CGContextStrokePath(context);
}

thanks.

A: 

UIGraphicsGetCurrentContext() refers to the UIView's context only when you're inside the -drawRect: method. To draw a line when you touch the screen, you need to use a variable to keep track on the finger's status.

@interface MyView : UIView {
   BOOL touchDown;
}
...

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
   touchDown = YES;
   [self setNeedsDisplay];
}
-(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
   touchDown = NO;
   [self setNeedsDisplay];
}
-(void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event {
   touchDown = YES;
   [self setNeedsDisplay];
}

-(void)drawRect:(CGRect)rect {
   CGContextRef context = UIGraphicsGetCurrentContext();
   ...
}
KennyTM