0

When the user clicks the screen a circle should be drawn where the user touch. Whats wrong with my code?

{
    BOOL _touchHasBegun;
    CGPoint whereUserClicked;
    float pointWhereUserClickedX;
    float pointWhereUserClickedY;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    _touchHasBegun = YES;
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, 0, 0, 225, 1);
    CGContextSetRGBFillColor(context, 0, 0, 255, 1);
    CGRect rectangle = CGRectMake(pointWhereUserClickedX, pointWhereUserClickedY, 10, 10);
    CGContextStrokeEllipseInRect(context, rectangle);
}
Nick Weaver
  • 47,228
  • 12
  • 98
  • 108

1 Answers1

0

Firstly, you need to call setNeedsDisplay to force drawRect: to be called. This can be done from your touch event handlers.

Secondly, you aren't drawing the circle around the touch point, but rather you are using the touch point as the corner of the circle.

This should correct that:

const CGFloat width = 10.0;
const CGFloat height = 10.0;
CGRect rectangle = CGRectMake(pointWhereUserClickedX - (width / 2.0),
                              pointWhereUserClickedY + (height / 2.0),
                              width,
                              height);
trojanfoe
  • 120,358
  • 21
  • 212
  • 242