This program draws a yellow star shape centered in a 200x200 frame with a shadow. It uses math to place points around a circle to form the star.
import SwiftUI
struct StarShape: Shape {
func path(in rect: CGRect) -> Path {
var path = Path()
let center = CGPoint(x: rect.midX, y: rect.midY)
let points = 5
let radius = min(rect.width, rect.height) / 2
let angle = Double.pi * 2 / Double(points * 2)
for i in 0..<(points * 2) {
let length = i.isMultiple(of: 2) ? radius : radius / 2
let x = center.x + CGFloat(cos(Double(i) * angle - Double.pi / 2)) * length
let y = center.y + CGFloat(sin(Double(i) * angle - Double.pi / 2)) * length
if i == 0 {
path.move(to: CGPoint(x: x, y: y))
} else {
path.addLine(to: CGPoint(x: x, y: y))
}
}
path.closeSubpath()
return path
}
}
struct ContentView: View {
var body: some View {
StarShape()
.fill(Color.yellow)
.frame(width: 200, height: 200)
.shadow(radius: 5)
}
}
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}