当我触摸屏幕时,我想在UIView的矩形中画一条线。请谁能帮我检查一下代码!
- (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);
}发布于 2010-08-08 16:16:08
只有当您在-drawRect:方法中时,UIGraphicsGetCurrentContext()才引用UIView的上下文。要在触摸屏幕时绘制一条线,需要使用一个变量来跟踪手指的状态。
@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);
}
}https://stackoverflow.com/questions/1220891
复制相似问题