UIGraphicsGetCurrentContext()
относится к контексту UIView только тогда, когда находится внутри метода -drawRect:
. Чтобы нарисовать линию при прикосновении к экрану, необходимо использовать переменную, чтобы отслеживать состояние пальца.
@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 = NO;
[self setNeedsDisplay];
}
-(void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
if(touchesDown) {
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);
}
}