Monday, June 15, 2026
HomeiOS Developmentios - Calculating if CGPoint is on a line section?

ios – Calculating if CGPoint is on a line section?

[ad_1]

I am on the lookout for a method to calculate if a CGPoint is on a line section. Are there any built-in strategies in Swift or any of Apple’s libraries?

I do not thoughts changing to a distinct kind so long as it’s a part of Apple’s code (e.g. much like how as a substitute of performing complicated calculations on double4x4 matrix, you may convert it to an SCNNode).


I rapidly got here up with brute drive answer, but it surely’s neither elegant, nor correct (given floating level comparisons in all places):

extension CGPoint {
  func isOnLineSegment(begin: CGPoint, finish: CGPoint) -> Bool {
    func worth(_ worth: CGFloat, isBetween one: CGFloat, and two: CGFloat) -> Bool {
      let a = [one, two].sorted()
      return a[0] <= worth && worth <= a[1]
    }

    let slope = (finish.y - begin.y) / (finish.x - begin.x)
    if slope.isInfinite {
      let isOnLine = x.isNearlyEqual(to: begin.x)
      let isWithinYValues = worth(y, isBetween: begin.y, and: finish.y)
      return isOnLine && isWithinYValues
    }

    let isOnLine = y.isNearlyEqual(to: slope * (x - begin.x) + begin.y) // y = m * (x - x1) + y1
    let isWithinXValues = worth(x, isBetween: begin.x, and: finish.x)

    return isOnLine && isWithinXValues
  }
}

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments