Created
March 9, 2020 03:14
-
-
Save uchcode/4b834e4cf5fa5fb3ef7d5685d1857f08 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
import SwiftUI | |
public struct Polygon: Shape { | |
public let sides: Int | |
public init(sides: Int) { self.sides = sides } | |
public func path(in rect: CGRect) -> Path { | |
let diameter = Double(min(rect.size.width, rect.size.height)) | |
let radius = diameter / 2.0 | |
let rad = Double.pi / 180.0 | |
let center = CGPoint(x: rect.size.width / 2.0, y: rect.size.height / 2.0) | |
return Path { path in | |
for i in 0 ..< sides { | |
let angle = Double(i) * (360.0 / Double(sides)) * rad | |
let a = center.x + CGFloat(sin(angle) * radius) | |
let b = center.y + CGFloat(cos(angle) * radius) | |
let point = CGPoint(x: a, y: -b + CGFloat(diameter)) | |
if i == 0 { | |
path.move(to: point) | |
} else { | |
path.addLine(to: point) | |
} | |
} | |
path.closeSubpath() | |
} | |
} | |
} | |
struct ContentView: View { | |
@State var sides = 3 | |
var body: some View { | |
VStack { | |
Spacer() | |
Polygon(sides: sides) | |
.fill(Color.blue) | |
.frame(width: 200, height: 200) | |
Spacer() | |
Stepper("Sides: \(sides)", value: $sides, in: 3...30) | |
.frame(width: 180) | |
} | |
.padding(50) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment