I'm looking for a way to calculate if a CGPoint is on a line segment. Are there any built-in methods in Swift or any of Apple's libraries?
I don't mind converting to a different type as long as it is part of Apple's code (e.g. similar to how instead of performing complex calculations on double4x4 matrix, you can convert it to an SCNNode).
I quickly came up with brute force solution, but it's neither elegant, nor accurate (given floating point comparisons everywhere):
extension CGPoint {
func isOnLineSegment(start: CGPoint, end: CGPoint) -> Bool {
func value(_ value: CGFloat, isBetween one: CGFloat, and two: CGFloat) -> Bool {
let a = [one, two].sorted()
return a[0] <= value && value <= a[1]
}
let slope = (end.y - start.y) / (end.x - start.x)
if slope.isInfinite {
let isOnLine = x.isNearlyEqual(to: start.x)
let isWithinYValues = value(y, isBetween: start.y, and: end.y)
return isOnLine && isWithinYValues
}
let isOnLine = y.isNearlyEqual(to: slope * (x - start.x) + start.y) // y = m * (x - x1) + y1
let isWithinXValues = value(x, isBetween: start.x, and: end.x)
return isOnLine && isWithinXValues
}
}
