Created
December 11, 2017 20:18
-
-
Save mpdroid/cea82e9603ac347709d93a1d5a2ee4fd to your computer and use it in GitHub Desktop.
Swift Arrowhead using CGPath
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Arrowhead pointing in the direction of "towards" CGPoint - supports triangular, pointy and diamond shaped heads as well | |
| // | |
| // Based on https://gist.github.com/mayoff/4146780// | |
| // | |
| import UIKit | |
| class ArrowHeadPath { | |
| class func create(from start: CGPoint, towards end: CGPoint, width: CGFloat, headLengthOuter: CGFloat, headLengthInner: CGFloat) -> CGPath { | |
| let length = hypot(end.x - start.x, end.y - start.y) | |
| func p(_ x: CGFloat, _ y: CGFloat) -> CGPoint { return CGPoint(x: x, y: y) } | |
| var points: [CGPoint] = [ | |
| p(headLengthOuter - headLengthInner , 0), | |
| p(0, width / 2), | |
| p(headLengthOuter, 0), | |
| p(0, -width / 2), | |
| ] | |
| let cosine = (end.x - start.x) / length | |
| let sine = (end.y - start.y) / length | |
| var transform = CGAffineTransform(a: cosine, b: sine, c: -sine, d: cosine, tx: start.x, ty: start.y) | |
| let path = CGMutablePath() | |
| path.addLines(between: points, transform: transform) | |
| path.closeSubpath() | |
| return path | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment