Created
December 18, 2019 12:58
-
-
Save mortenbekditlevsen/b318acee932d8835298ff949537031d1 to your computer and use it in GitHub Desktop.
Half failed attempt at a koch snowflake. Looks pretty tho'! ;-)
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
import SwiftUI | |
struct Triflake: View { | |
let angle: Angle | |
let level: Int | |
init(angle: Angle, level: Int) { | |
self.angle = angle | |
self.level = level | |
} | |
var body: some View { | |
if level == 0 { | |
return GeometryReader { g in | |
ZStack { | |
Triangle(angle: self.angle) | |
}.frame(width: g.size.width, height: g.size.width) | |
}.eraseToAnyView() | |
} else { | |
return GeometryReader { g in | |
ZStack { | |
Triflake(angle: self.angle, level: self.level - 1).scaleEffect(1 / 3).offset(x: g.size.width / 2 - g.size.width / 6, y: 0) | |
Triflake(angle: self.angle, level: self.level - 1).scaleEffect(1 / 3).offset(x: g.size.width / 2 - g.size.width / 6, y: 0).rotationEffect(Angle(degrees: 120)) | |
Triflake(angle: self.angle, level: self.level - 1).scaleEffect(1 / 3).offset(x: g.size.width / 2 - g.size.width / 6, y: 0).rotationEffect(Angle(degrees: 240)) | |
Triflake(angle: self.angle, level: self.level - 1) | |
}.frame(width: g.size.width, height: g.size.width) | |
.rotationEffect(self.angle) | |
.animation(Animation.default.delay(0.1 * (5 - Double(self.level))).speed(0.25)) | |
}.eraseToAnyView() | |
} | |
} | |
} | |
func + (left: CGPoint, right: CGPoint) -> CGPoint { | |
return CGPoint(x: left.x + right.x, y: left.y + right.y) | |
} | |
func - (left: CGPoint, right: CGPoint) -> CGPoint { | |
return CGPoint(x: left.x - right.x, y: left.y - right.y) | |
} | |
struct Triangle: View { | |
let angle: Angle | |
init(angle: Angle) { | |
self.angle = angle | |
} | |
var body: some View { | |
GeometryReader { g in | |
Path { path in | |
let center = CGPoint(x: g.size.width / 2, y: g.size.height / 2) | |
let v = CGPoint(x: g.size.width / 2, y: 0) | |
let t = CGAffineTransform(rotationAngle: 2 * .pi / 3) | |
let rotated = v.applying(t) | |
path.move(to: center + v) | |
path.addLine(to: center + rotated) | |
path.addLine(to: center + rotated.applying(t)) | |
path.addLine(to: center + v) | |
}.rotation(self.angle).foregroundColor(Color.blue.opacity(0.25)) | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment