0

I'm placing items along a UIBezierPath. I would like to be able to specify how many points apart these items are. In other words, place an item every x points along the path.

I found very nice clean code for something similar here: https://andreygordeev.com/2017/03/13/uibezierpath-closest-point/

With this, I have placed the items, but it places a certain total number of items along the path, evenly distributed across the segments of a path. This means that a segment that is 100 points long will have the items placed much closer together compared with a segment that is 1000 points long.

So, I would like to find the length of each segment and then make t, in the referenced code, equal to distance-between-points/length-of-segment.

I wrote this function for the distance of linear segments:

/// Calculates distance between points
private func calculateLinearDistance(p1: CGPoint, p2: CGPoint) -> CGFloat {
    let width = p1.x - p2.x
    let height = p1.y - p2.y
    let distance = sqrt(pow(width,2)+pow(height,2))
    return distance
}

Then I adapted the referenced code for the linear segments from:

case .addLineToPoint:
    // Line
    for i in 0...capacityPerPiece {
        let t = CGFloat(i) / CGFloat(capacityPerPiece)
        let point = calculateLinear(t: t, p1: startPoint, p2: endPoint)
        lookupTable.append(point)
    }

to:

case .addLineToPoint:
    // Line

    var i:CGFloat = 0.0
    let distance = calculateLinearDistance(p1: startPoint, p2: endPoint) //new

    while (i < distance) {

        // let t = CGFloat(i) / CGFloat(capacityPerPiece) replaced

        //DEBUG: use variable instead of 7
        i = i + 7
        let t = i/distance
        let point = calculateLinear(t: t, p1: startPoint, p2: endPoint)
        lookupTable.append(point)
    }

And that works great!

But, what formulas should I use to find the lengths for .addQuadCurveToPoint and .addCurveToPoint?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
TheCodePig
  • 122
  • 10
  • You could try adapting https://stackoverflow.com/a/26131682/77567 which solves this problem in Objective-C. – rob mayoff Jul 07 '17 at 21:15
  • You could even use that code directly, since you can call Objective-C code from Swift. – rob mayoff Jul 07 '17 at 21:15
  • I will dig into that code. thx I think I need to review the calculus concepts. For now, I treated all path segments as though they were straight lines (just used distance). It works for all my test cases, but I know eventually it will cause a problem. – TheCodePig Jul 11 '17 at 00:03

0 Answers0