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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With