Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if CGPoint within polygon

I have a set of CGPoints which make up a polygon shape, how can I detect if a single CGPoint is inside or outside of the polygon?

Say, the shape was a triangle and the CGPoint was moving hoizontally, how could I detect when it crossed the triangle line?

I can use CGRectContainsPoint when the shape is a regular 4-sided shape but I can't see how I would do it with an odd shape.

like image 248
JWood Avatar asked Jan 21 '12 11:01

JWood


2 Answers

You can create a CG(Mutable)PathRef (or a UIBezierPath that wraps a CGPathRef) from your points and use the CGPathContainsPoint function to check if a point is inside that path. If you use UIBezierPath, you could also use the containsPoint: method.

like image 170
omz Avatar answered Nov 09 '22 17:11

omz


For that you need to write one method that implements a point inside polygon algorithm.

This method will take an array with N points (the polygon) as an argument and one specific point. It should return true if the point is inside the polygon and false if not.

See this great answer on S.O.

like image 2
Ankur Avatar answered Nov 09 '22 15:11

Ankur