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.
- Why does this happen?
- 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!