import Renderer import SwiftUI /// A burst of paper confetti thrown up from the middle of the view, tumbling as it falls out of /// the bottom over `duration` seconds from when the view appears. Pieces in the paper's colours /// show its front on one side and its back on the other. struct Confetti: View { nonisolated static let duration = 2.5 @State private var pieces = (0..<90).map { _ in Piece() } @State private var start = Date.now var body: some View { TimelineView(.animation) { timeline in Canvas { context, size in let elapsed = timeline.date.timeIntervalSince(start) for piece in pieces { piece.draw(in: context, size: size, at: elapsed) } } } } } private let front = colour(PaperRenderer.frontColour) private let back = colour(PaperRenderer.backColour) private let accents = [Color(red: 0.96, green: 0.74, blue: 0.20), Color(red: 0.16, green: 0.58, blue: 0.56), Color(red: 0.26, green: 0.44, blue: 0.86)] private func colour(_ c: SIMD4) -> Color { Color(red: Double(c.x), green: Double(c.y), blue: Double(c.z)) } private struct Piece { /// Where it is thrown from and its initial velocity, as fractions of the view's size. let origin = SIMD2(Double.random(in: 0.35...0.65), Double.random(in: 0.3...0.4)) let velocity = SIMD2(Double.random(in: -0.7...0.7), Double.random(in: -1.6...(-0.8))) let size = CGSize(width: Double.random(in: 6...11), height: Double.random(in: 4...9)) /// Radians per second in the plane of the screen and about the piece's own long axis. let spin = Double.random(in: -6...6), tumble = Double.random(in: 4...10) let phase = Double.random(in: 0...(2 * .pi)) /// One colour on each side. let sides: (Color, Color) = Bool.random() ? (front, back) : { let c = accents.randomElement()!; return (c, c) }() /// Air drag and the speed it falls at once drag has taken out the throw, per second and in /// fractions of the view's height per second. private static let drag = 2.5, fallSpeed = 0.6 func draw(in context: GraphicsContext, size view: CGSize, at t: Double) { guard t >= 0, t < Confetti.duration else { return } let slowed = (1 - exp(-Self.drag * t)) / Self.drag let x = origin.x + velocity.x * slowed + 0.02 * sin(3 * t + phase) let y = origin.y + (velocity.y - Self.fallSpeed) * slowed + Self.fallSpeed * t let turn = cos(tumble * t + phase) var piece = context piece.opacity = min(1, (Confetti.duration - t) / 0.4) piece.translateBy(x: x * view.width, y: y * view.height) piece.rotate(by: .radians(spin * t + phase)) piece.scaleBy(x: 1, y: turn) let rect = CGRect(x: -size.width / 2, y: -size.height / 2, width: size.width, height: size.height) piece.fill(Path(rect), with: .color(turn >= 0 ? sides.0 : sides.1)) } }