krz/daybyday

iOS learning games for young children: days, months, seasons, numbers, letters, animals and more. education ios kids swift https://krz.sh/apps/daybyday/

DayByDay/Quiz/ShakeRain.swift

main
daybyday/DayByDay/Quiz/ShakeRain.swift history · blame · raw

72 lines · 2477 bytes

3 symbols in this file
 1//
 2//  ShakeRain.swift
 3//  DayByDay
 4//
 5
 6import SwiftUI
 7import UIKit
 8
 9extension Notification.Name {
10    static let deviceDidShake = Notification.Name("deviceDidShake")
11}
12
13extension UIWindow {
14    open override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
15        if motion == .motionShake {
16            NotificationCenter.default.post(name: .deviceDidShake, object: nil)
17        }
18        super.motionEnded(motion, with: event)
19    }
20}
21
22extension View {
23    func onShake(_ action: @escaping () -> Void) -> some View {
24        onReceive(NotificationCenter.default.publisher(for: .deviceDidShake)) { _ in action() }
25    }
26}
27
28/// Rain falling over the screen for a few seconds. With Reduce Motion the
29/// drops hold still and fade.
30struct RainOverlay: View {
31    static let duration = 3.0
32    static let dropColor = Color(red: 0.10, green: 0.40, blue: 0.85)
33
34    let isActive: Bool
35
36    @Environment(\.accessibilityReduceMotion) private var reduceMotion
37    @State private var start = Date()
38
39    private static let drops: [(x: Double, phase: Double, speed: Double)] = {
40        var rng = SystemRandomNumberGenerator()
41        return (0..<70).map { _ in
42            (Double.random(in: 0...1, using: &rng), Double.random(in: 0...1, using: &rng),
43             Double.random(in: 0.8...1.3, using: &rng))
44        }
45    }()
46
47    var body: some View {
48        Group {
49            if isActive {
50                TimelineView(.animation) { timeline in
51                    Canvas { context, size in
52                        let t = timeline.date.timeIntervalSince(start)
53                        guard t < Self.duration else { return }
54                        let fade = min(1, (Self.duration - t) / 0.6)
55                        context.opacity = fade
56                        for drop in Self.drops {
57                            let y = reduceMotion
58                                ? drop.phase
59                                : (drop.phase + t * drop.speed * 0.9).truncatingRemainder(dividingBy: 1.1) - 0.05
60                            let rect = CGRect(x: drop.x * size.width, y: y * size.height, width: 5, height: 22)
61                            context.fill(Path(roundedRect: rect, cornerRadius: 2.5), with: .color(Self.dropColor))
62                        }
63                    }
64                }
65            }
66        }
67        .allowsHitTesting(false)
68        .onChange(of: isActive) { _, active in
69            if active { start = Date() }
70        }
71    }
72}