-
-
Save benjohnde/2ce3d6878e8c3fb379cac1f9814bfde8 to your computer and use it in GitHub Desktop.
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
// without turtle drawing a hexagon is math heavy and not trivial to modify | |
let numberOfSides: CGFloat = 6 | |
let radiusOuterCircle: CGFloat = 30 | |
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) + centerX) | |
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 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
// with turtle the code is clear, composable and easy to modify | |
// but it’s less efficient for sure | |
let sideLength = square.width / 2 | |
let turtle = UITurtlePath() | |
for _ in 0..<6 { | |
turtle.scuttle(sideLength) | |
turtle.turn(.pi / 3) | |
} |
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
/// “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