👔Polygon

⬆️ 需要: Vector2D, floating +−⨉÷ int
// 2022.03.01
import SwiftUI
import Extensions // FloatingPoint+
import Protocols // Vector2D
/// an animatable polygon shape
/// ```
/// Polygon(sides: 6, scale: 1.2)
/// Polygon(5)
/// ```
public struct Polygon: Shape {
var sides: CGFloat
var scale: CGFloat = 1.0
public init(sides: CGFloat, scale: CGFloat = 1.0) {
self.sides = sides
self.scale = scale
}
// ⭐️ `animatableData` (AnimatablePair)
public var animatableData: AnimatablePair<CGFloat, CGFloat> {
get { AnimatablePair(sides, scale) }
// ⭐️ set new animation value
set {
sides = newValue.first
scale = newValue.second
}
}
public func path(in rect: CGRect) -> Path {
let r = scale * rect.minSide / 2 // radius
let c = rect.center // polygon center
let a0 = -0.5 * CGFloat.pi // start angle
let a = CGFloat.pi / sides * 2 // difference to next angle
let n = Int(sides.rounded(.up)) // integral sides
return Path { path in
path.move(to: c + .polar(r, a0))
for i in 1..<n {
path.addLine(to: c + .polar(r, a0 + a * i))
}
path.closeSubpath()
}
}
}
// convenience init
extension Polygon {
/// `Polygon(3)`
public init(_ n: CGFloat) {
self.init(sides: n)
}
}
Last updated
Was this helpful?