Last active
May 5, 2023 12:53
-
-
Save mxcl/8a2d9c1b1c0063f2a71e24f9fe045d43 to your computer and use it in GitHub Desktop.
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
// 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() |
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
// 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) | |
} |
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
/// “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