Skip to content

Instantly share code, notes, and snippets.

@atomoil
Created July 14, 2020 22:42
Show Gist options
  • Select an option

  • Save atomoil/26b4405bbcc4fd0ac8b596c137a9cbfe to your computer and use it in GitHub Desktop.

Select an option

Save atomoil/26b4405bbcc4fd0ac8b596c137a9cbfe to your computer and use it in GitHub Desktop.

Revisions

  1. atomoil created this gist Jul 14, 2020.
    25 changes: 25 additions & 0 deletions CGPoint+perpedicular.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@

    extension CGPoint {
    func midBetween(_ other: CGPoint) -> CGPoint {
    return CGPoint(x: (self.x + other.x) / 2.0,
    y: (self.y + other.y) / 2.0)
    }

    func perpedicularTo(_ other: CGPoint, distance: CGFloat) -> (CGPoint, CGPoint) {
    // Vector from p to p1;
    var diff = CGPoint(x: other.x - self.x, y: other.y - self.y);
    // Distance from p to p1:
    let length = CGFloat(hypotf(Float(diff.x), Float(diff.y)))
    // Normalize difference vector to length 1:
    diff.x /= length;
    diff.y /= length;
    // Compute perpendicular vector:
    let perp = CGPoint(x: -diff.y, y: diff.x)

    //let markLength = 3.0; // Whatever you need ...
    let a = CGPoint(x: self.x + perp.x * distance/2, y: self.y + perp.y * distance/2)
    let b = CGPoint(x: self.x - perp.x * distance/2, y: self.y - perp.y * distance/2)

    return (a, b)
    }
    }