Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting stroked uibezierpath contains point

I'm drawing a stroked path in my view. And I'm trying to see if the stroked path contains a specific point. But it the contains method does not detect if the point is in the stroked path.

func checkCollision(currentPoint:CGPoint) -> CustomShape?{
    for shape in customShapes {
        //Check if current shapes uibezierpath contains a point
        if (shape.path.contains(currentPoint)) {
            return shape
        }
    }
    return nil
}
like image 522
Abdullahi Avatar asked Nov 16 '25 12:11

Abdullahi


1 Answers

Swift 5.x

You can use this extension for a quick answer:

extension UIBezierPath {
    func isInsideBorder(_ pos:CGPoint, tolleranceWidth:CGFloat = 2.0)->Bool{
        let pathRef = cgPath.copy(strokingWithWidth: tolleranceWidth, lineCap: CGLineCap.butt, lineJoin: CGLineJoin.round, miterLimit: 0)
        let pathRefMutable = pathRef.mutableCopy()
        if let p = pathRefMutable {
            p.closeSubpath()
            return p.contains(pos)
        }
        return false
    }
}

Usage:

var currentPoint:CGPoint= CGPoint.zero
if yourBeizerPath.isInsideBorder(currentPoint, tolleranceWidth:3.0) {
   /// Let's go, it's inside..
}
like image 197
Alessandro Ornano Avatar answered Nov 19 '25 03:11

Alessandro Ornano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!