如何使用Core Graphics在我的触摸位置绘制一个圆圈?

新的程序员在这里。 我在尝试使用Core Graphics在我的触摸位置周围绘制描边弧时出现问题。 我有方法来绘制圆圈工作正常,我已经testing,并正在注册触摸,当我点击屏幕,但是当我尝试调用方法来绘制圆时,我点击,我得到错误“CG​​ContextBlahBlah:invalid context为0x0"

认为这是因为我没有在drawRect :()中调用方法。

那么我怎么能够通过触摸来调用这个方法呢? 另外,如何在我的绘图方法中使用“CGPoint locationOfTouch”作为参数?

这是我正在使用的代码块。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint locationOfTouch = [touch locationInView:self]; [self drawTouchCircle:(locationOfTouch)]; [self setNeedsDisplay]; } -(void)drawTouchCircle:(CGPoint)locationOfTouch { CGContextRef ctx= UIGraphicsGetCurrentContext(); CGContextSaveGState(ctx); CGContextSetLineWidth(ctx,5); CGContextSetRGBStrokeColor(ctx,0.8,0.8,0.8,1.0); CGContextAddArc(ctx,locationOfTouch.x,locationOfTouch.y,30,0.0,M_PI*2,YES); CGContextStrokePath(ctx); } 

先谢谢您的帮助!

你是对的。 问题是,你不应该自己调用drawTouchCircle ,而应该实现一个为你调用它的drawRect方法,因此你的touches方法只需要调用setNeedsDisplay ,而drawRect将负责其余的部分。 因此,您可能想将触摸位置保存在类属性中,然后在drawRect检索:

 @interface View () @property (nonatomic) BOOL touched; @property (nonatomic) CGPoint locationOfTouch; @end @implementation View - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; self.touched = YES; UITouch *touch = [touches anyObject]; self.locationOfTouch = [touch locationInView:self]; [self setNeedsDisplay]; } - (void)drawTouchCircle:(CGPoint)locationOfTouch { CGContextRef ctx= UIGraphicsGetCurrentContext(); CGRect bounds = [self bounds]; CGPoint center; center.x = bounds.origin.x + bounds.size.width / 2.0; center.y = bounds.origin.y + bounds.size.height / 2.0; CGContextSaveGState(ctx); CGContextSetLineWidth(ctx,5); CGContextSetRGBStrokeColor(ctx,0.8,0.8,0.8,1.0); CGContextAddArc(ctx,locationOfTouch.x,locationOfTouch.y,30,0.0,M_PI*2,YES); CGContextStrokePath(ctx); } - (void)drawRect:(CGRect)rect { if (self.touched) [self drawTouchCircle:self.locationOfTouch]; } @end