Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// without turtle drawing a hexagon is math heavy and not trivial to modify
let numberOfSides: CGFloat = 6
let radiusOuterCircle: CGFloat = bounds.width
let sideLength = radiusOuterCircle / 2
let theta = (CGFloat.pi * 2) / numberOfSides
let centerX = sideLength / 2
let centerY = sideLength / 2
let initialPoint = CGPoint(x: radiusOuterCircle * cos(2 * CGFloat.pi * 0/numberOfSides + theta) + centerX, y: radiusOuterCircle * sin(2 * CGFloat.pi * 0/numberOfSides + theta) + centerY)
let shapePath = UIBezierPath()
shapePath.move(to: initialPoint)
for i in 1...Int(numberOfSides) {
shapePath.addLine(to: CGPoint(x: radiusOuterCircle * cos(2 * CGFloat.pi * CGFloat(i) / numberOfSides + theta) + centerX, y: radiusOuterCircle * sin(2 * CGFloat.pi * CGFloat(i) / numberOfSides + theta) + centerY))
}
shapePath.close()
// with turtle the code is clear, composable and easy to modify
// but it’s less efficient for sure
let sideLength = bounds.width / 2 // math is beautiful, a hexagon’s side length is half the containing square’s dimension
let turtle = UITurtlePath()
for _ in 0..<6 {
turtle.scuttle(sideLength)
turtle.turn(.pi / 3)
}
/// “draw” shapes like moving a turtle around
class UITurtlePath {
let path = UIBezierPath()
init() {
path.move(to: .zero)
}
func scuttle(_ amount: CGFloat) {
path.addLine(to: .init(x: amount, y: 0))
path.apply(CGAffineTransform(translationX: -amount, y: 0))
}
func hop(_ amount: CGFloat) {
path.move(to: .init(x: amount, y: 0))
path.apply(CGAffineTransform(translationX: -amount, y: 0))
}
func turn(_ radians: CGFloat) {
path.apply(CGAffineTransform(rotationAngle: radians))
}
func close() {
let pt = path.currentPoint
path.addLine(to: .init(x: 0, y: 0))
path.apply(CGAffineTransform(translationX: -pt.x, y: -pt.y))
path.close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.