Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Created December 28, 2016 03:50
Show Gist options
  • Save kristopherjohnson/a42e13dacd618bf0fd5b46a357b7731d to your computer and use it in GitHub Desktop.
Save kristopherjohnson/a42e13dacd618bf0fd5b46a357b7731d to your computer and use it in GitHub Desktop.
Calculate Y-axis distance between a point and a line segment.
import CoreGraphics
extension CGPoint {
/// Calculate Y-axis distance between a point and a line segment.
///
/// - parameter endpointA: One endpoint of the line segment.
/// - parameter endpointB: The other endpoint of the line segment.
///
/// - returns: Distance, or `nil` if this point's x-coordinate is not between those of the endpoints.
func distanceAboveLineSegment(endpointA: CGPoint,
endpointB: CGPoint) -> CGFloat?
{
// Fail if endpoints are on a vertical line.
if endpointA.x == endpointB.x {
return nil
}
// Swap endpoints if necessary so that endpointLeft is the leftmost point.
var endpointLeft = endpointA
var endpointRight = endpointB
if endpointLeft.x > endpointRight.x {
swap(&endpointLeft, &endpointRight)
}
let x = self.x
// If not over the line segment, fail.
if x < endpointLeft.x || endpointRight.x < x {
return nil
}
// Find the y-coordinate where a vertical line crosses the line segment.
let slope = (endpointRight.y - endpointLeft.y) / (endpointRight.x - endpointLeft.x)
let dx = x - endpointLeft.x
let dy = slope * dx
let yIntercept = endpointLeft.y + dy
// Return distance.
return self.y - yIntercept
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment