tags:

views:

77

answers:

1

Hello guys!

I'm trying to detect if a rectangle or a circle contains a point. It is not so hard, but I want to know that is there any built-in method in objective c for this? Thanks!

+2  A: 

For rectangles (as NSRects) there is the Foundation function NSPointInRect():

NSPoint somePoint = //The point you want to test for
NSRect someRect = //The rectangle you want to test in

BOOL rectContainsPoint = NSPointInRect(somePoint, someRect);

For circles, you can use the NSBezierPath instance method containsPoint:

NSBezierPath *circlePath = //Assume this is instantiated to a circle path
NSPoint somePoint = //The point you want to test for

BOOL circleContainsPoint = [circlePath containsPoint:somePoint];

Equally if you have a rectangular path you could use containsPoint: to test whether the point is in that rectangle.

Edit: As NSResponder pointed out, creating a full path object may not always be the most efficient method – if you already have circle paths for some kind of drawing or something then yes, but there are probably other more efficient ways of doing it. However using paths is a built-in method of doing it.

Perspx
I wouldn't create a path to test for a point in a circle. You can just check the distance from the point to the center.
NSResponder
Yeah in terms of efficiency, unless you are already working with an `NSBezierPath` object you're probably right, although `Tojas` was asking for built-in methods. Fixed the answer anyway.
Perspx