Last active
March 2, 2018 01:12
-
-
Save Jesse-calkin/fbcf0a0f014848f9e967 to your computer and use it in GitHub Desktop.
UIBezierPath extension adding convenience initializers for basic shapes.
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
import UIKit | |
let TWO_PI = .pi * 2.0 | |
extension UIBezierPath { | |
static func triangle(p1: CGPoint, p2: CGPoint, p3: CGPoint) -> UIBezierPath { | |
return UIBezierPath(tri: p1, p2: p2, p3: p3) | |
} | |
convenience init(tri p1: CGPoint, p2: CGPoint, p3: CGPoint) { | |
self.init() | |
move(to:p1) | |
addLine(to: p2) | |
addLine(to: p3) | |
close() | |
} | |
convenience init(quad p1: CGPoint, p2: CGPoint, p3: CGPoint, p4: CGPoint) { | |
self.init() | |
move(to:p1) | |
addLine(to: p2) | |
addLine(to: p3) | |
addLine(to: p4) | |
close() | |
} | |
convenience init(mtn start: CGPoint, end: CGPoint, steps: Int, variance: Int) { | |
self.init() | |
move(to:start) | |
let step = (end.x - start.x) / CGFloat(steps) | |
for i in 1..<steps { | |
let x = start.x + (step * CGFloat(i)) | |
let y = start.y + CGFloat(arc4random_uniform(UInt32(variance))) | |
let p = CGPoint(x: x, y: y) | |
addLine(to: p) | |
} | |
addLine(to: end) | |
} | |
convenience init(line start: CGPoint, end: CGPoint) { | |
self.init() | |
move(to:start) | |
addLine(to: end) | |
} | |
convenience init(poly point: CGPoint, radius: Float, points: Int) { | |
self.init() | |
let angle = Float(TWO_PI / Double(points)) | |
var points = [CGPoint]() | |
var a: Float = 0.0 | |
while a < Float(TWO_PI) { | |
let sx = point.x + CGFloat(cos(a) * radius) | |
let sy = point.y + CGFloat(sin(a) * radius) | |
points.append(CGPoint(x: sx, y: sy)) | |
a += angle | |
} | |
move(to:points.first!) | |
points.removeFirst() | |
points.forEach { addLine(to: $0) } | |
close() | |
} | |
convenience init(star point: CGPoint, innerRadius: Float, outerRadius: Float, points: Int) { | |
self.init() | |
let angle = Float(TWO_PI / Double(points)) | |
let halfAngle = angle / 2.0 | |
var points = [CGPoint]() | |
var a: Float = 0.0 | |
while a < Float(TWO_PI) { | |
var sx = point.x + CGFloat(cos(a) * outerRadius) | |
var sy = point.y + CGFloat(sin(a) * outerRadius) | |
points.append(CGPoint(x: sx, y: sy)) | |
sx = point.x + CGFloat(cos(a + halfAngle) * innerRadius) | |
sy = point.y + CGFloat(sin(a + halfAngle) * innerRadius) | |
points.append(CGPoint(x: sx, y: sy)) | |
a += angle | |
} | |
move(to:points.first!) | |
points.removeFirst() | |
points.forEach { addLine(to: $0) } | |
close() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment