vishal jain
vishal jain

Reputation: 31

How to detect a tap inside open(not closed) BezierPath in swift

[enter image description here][1]I have a bezierpath for an unclosed structure. I want to detect tap only when clicked on the path, and not for taps on the area enclosed by the path.If I use path.contains, it giving me true even for taps enclosed by path.

bezier.contains(touchPoint)

The Path Image has grey path which is created using code below, I would like to detect the clicks on gray portions only and not inside the area surrounded by gray portion.

let color:UIColor = getColor(structure.category)
let bpath:UIBezierPath = UIBezierPath()
beziers.append(bpath);
bpath.move(to: structure.points[0].fromPoint)
for point in structure.points {
    bpath.addCurve(to: point.toPoint, controlPoint1:point.controlPointOne, controlPoint2: point.controlPointTwo)
}
bpath.lineWidth = 5.0
color.set()
bpath.stroke()

Upvotes: 1

Views: 868

Answers (3)

adam.wulf
adam.wulf

Reputation: 2169

@matt's solution below is a good way to determine if a point near the original path. It's similar to the solution in this question that uses CGPathCreateCopyByStrokingPath.

An alternative option would be to use the ClippingBezier library I wrote, which contains a closestPointOnPathTo: method. You could then, in pseudocode:

CGPoint pointOnPath = [myBezierPath closestPointOnPathTo:touchPoint];
CGFloat distToPath = distanceBetweenPoints(pointOnPath, touchPoint);
if(distToPath < 5) ...

This may be overkill depending on what you need, or might give some additional useful bezier tools depending on what else you'll do with your paths.

Upvotes: 0

matt
matt

Reputation: 535925

Turn your strokes to a closed path by taking the UIBezierPath's path property, which is a CGPath, and calling copy(strokingWithWidth:) on that CGPath. Now you have a closed path (or more than one closed path) and you can use the CGPath contains method successfully.

Upvotes: 2

kkodev
kkodev

Reputation: 2607

It's not easy to detect whether a point lies on any bezierPath but I have a trick for you.

To detect whether a point lies on any shape, render it in a colour C to a bitmap, get the pixel corresponding to your coordinate and check colour of that pixel. If it's C then the point lies on your shape, otherwise it doesn't.

Upvotes: 0

Related Questions