21

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.

JWood
  • 2,804
  • 2
  • 39
  • 64

4 Answers4

30

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.

omz
  • 53,243
  • 5
  • 129
  • 141
2

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.

Community
  • 1
  • 1
Ankur
  • 5,086
  • 19
  • 37
  • 62
1

Here is the implementation in Swift:

extension CGPoint {
    
    func isInsidePolygon(vertices: [CGPoint]) -> Bool {
        guard vertices.count > 0 else { return false }
        var i = 0, j = vertices.count - 1, c = false, vi: CGPoint, vj: CGPoint
        while true {
            guard i < vertices.count else { break }
            vi = vertices[i]
            vj = vertices[j]
            if (vi.y > y) != (vj.y > y) &&
                x < (vj.x - vi.x) * (y - vi.y) / (vj.y - vi.y) + vi.x {
                c = !c
            }
            j = i
            i += 1
        }
        return c
    }
}
Alexander Volkov
  • 7,904
  • 1
  • 47
  • 44
bzz
  • 5,556
  • 24
  • 26
0

Swift 3

A simpler way using Swift 3, is using UIBezierPath contains method.

When creating an instance of CAShapeLayer, make sure to set the accessibilityPath

shapeLayer.path = bazierPath.cgPath
shapeLayer.accessibilityPath = bazierPath

Checking if path contains touch location.

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let point = touches.first?.location(in: self) else { return }

    for shape in layer.sublayers ?? [] where shape is CAShapeLayer {
        guard let layer = shape as? CAShapeLayer,
            let bazier = layer.accessibilityPath else { continue }

        // Handle touch
        print(bazier.contains(point))
    }
}
Tal Zion
  • 6,308
  • 3
  • 50
  • 73