发行CGContext

时间:2009-08-03 06:31:44

标签: iphone

当我触摸屏幕时,我想在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);
}

1 个答案:

答案 0 :(得分:2)

UIGraphicsGetCurrentContext()仅在您在-drawRect:方法内时才引用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);
   }
}