开发者

How do I prevent my view from getting cleared every time I draw a circle using Core Graphics?

I'm diving in to 2D graphics programming on the iPad and I want to draw circles where the user touched the screen. Here's my simple code to accomplish this...

View Class

-(void)setTouchPoint:(CGPoint)point
{
 touchPoint.x = point.x;
 touchPoint.y = point.y;

 [self setNeedsDisplay];
}

-(id)initWithFrame:(CGRect)frame
{
 self = [super initWithFrame:frame];
 if(self != nil)
 {
  self.backgroundColor = [UIColor whiteColor];
  self.opaque = YES;
  self.clearsContextBeforeDrawing = YES;
 }
 return self;
}



-(void)drawInContext:(CGContextRef)context
{
 // Drawing with a white stroke color
 CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 1.0);
 // And draw with a blue fill color
 CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);
 // Draw them with a 2.0 stroke width so they are a bit more visible.
 CGContextSetLineWidth(context, 2.0);

 // Add an ellipse circumscribed in the given rect to the current path, then stroke it
 CGContextAddEllipseInRect(context, CGRectMake(touchPoint.x - 10, touchPoint.y - 10, 20, 20));
 CGContextStrokePath(context);

}

-(void)drawRect:(CGRect)rect
{
 [self drawInContext:UIGraphicsGetCurrentContext()];
}

Every time the user touches the screen, 开发者_开发百科the view is cleared, causing the previous circle to be erased, and a new circle is drawn where the user touched.

  1. Why does this happen?
  2. How can I prevent the previous circles from being cleared?

I tried setting the self.clearsContextBeforerDrawing property to NO, but that didn't fix it.

Thanks so much in advance for all your help!


You can draw circles on a separate layer and in drawRect just copy it.

See CGLayerCreateWithContext, CGLayerGetContext, CGContextDrawLayerInRect function for details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜