Last active
May 25, 2021 14:49
-
-
Save niczyja/a50ea5a0960ba95d8c676e79fb8cc53d to your computer and use it in GitHub Desktop.
Drawing shapes (arrow, point) using CGMutablePath. Based on: https://gist.github.com/mwermuth/07825df27ea28f5fc89a
This file contains 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
extension CGMutablePath { | |
func addArrow(to point: CGPoint, tailWidth: CGFloat = 4.0, headWidth: CGFloat = 10.0, headLength: CGFloat = 14.0) { | |
let length = hypot(point.x - currentPoint.x, point.y - currentPoint.y) | |
let tailLength = length - headLength | |
let points: [CGPoint] = [ | |
CGPoint(x: 0.0, y: tailWidth / 2), | |
CGPoint(x: tailLength, y: tailWidth / 2), | |
CGPoint(x: tailLength, y: headWidth / 2), | |
CGPoint(x: length, y: 0.0), | |
CGPoint(x: tailLength, y: -headWidth / 2), | |
CGPoint(x: tailLength, y: -tailWidth / 2), | |
CGPoint(x: 0.0, y: -tailWidth / 2) | |
] | |
let cosine: CGFloat = (point.x - currentPoint.x) / length | |
let sine: CGFloat = (point.y - currentPoint.y) / length | |
let transform = CGAffineTransform(a: cosine, b: sine, c: -sine, d: cosine, tx: currentPoint.x, ty: currentPoint.y) | |
addLines(between: points, transform: transform) | |
} | |
func markPoint(at point: CGPoint, crossSize: CGFloat = 9.0) { | |
move(to: CGPoint(x: point.x - crossSize / 2, y: point.y - crossSize / 2)) | |
addLine(to: CGPoint(x: point.x + crossSize / 2, y: point.y + crossSize / 2)) | |
move(to: CGPoint(x: point.x - crossSize / 2, y: point.y + crossSize / 2)) | |
addLine(to: CGPoint(x: point.x + crossSize / 2, y: point.y - crossSize / 2)) | |
} | |
} |
Point:
let path = CGMutablePath()
path.move(to: location)
path.markPoint(at: location)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
let path = CGMutablePath()
path.move(to: start)
path.addArrow(to: end)