Skip to content

Instantly share code, notes, and snippets.

@uchcode
Created March 9, 2020 03:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uchcode/4b834e4cf5fa5fb3ef7d5685d1857f08 to your computer and use it in GitHub Desktop.
Save uchcode/4b834e4cf5fa5fb3ef7d5685d1857f08 to your computer and use it in GitHub Desktop.
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