Tojas
Tojas

Reputation: 21

Objective C shapes and points

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!

Upvotes: 0

Views: 557

Answers (1)

Alex Rozanski
Alex Rozanski

Reputation: 38005

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.

Upvotes: 2

Related Questions