3

Given the center point and radius of a circle, how do I know if a certain point (x,y) is in the circle? Anyone knows it? Thanks.

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
james
  • 51
  • 2
  • 3
  • 4
    general question has no relation to your tags....And its easily searchable – Mitch Wheat Sep 13 '11 at 08:34
  • 2
    In short: Determine the [distance from the center to the point](http://en.wikipedia.org/wiki/Pythagoras#Pythagorean_theorem), then compare that to the radius. – Markus Hedlund Sep 13 '11 at 08:43
  • Not specifically Objective-C, but this should help. You should be able to convert the functions fairly easily: [http://stackoverflow.com/questions/481144/how-do-you-test-if-a-point-is-inside-a-circle](http://stackoverflow.com/questions/481144/how-do-you-test-if-a-point-is-inside-a-circle) – Max MacLeod Sep 13 '11 at 08:36

1 Answers1

8

Originally you asked for Objective-C.

CGFloat DistanceBetweenTwoPoints(CGPoint point1,CGPoint point2)
{
    CGFloat dx = point2.x - point1.x;
    CGFloat dy = point2.y - point1.y;
    return sqrt(dx*dx + dy*dy );
};

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint point = [[touches anyObject] locationInView:self];
    CGFloat distance = DistanceBetweenTwoPoints(self.circleCenter, point);
    if(distance < self.radius){
        //inside the circle
    }
}

This code assumes, that you dealing with the circle inside a subclassed View.

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178