import QuartzCore import SwiftUI import UIKit /// Core Animation rotates the hosted artwork without redrawing the image on every frame. struct SpinningAlbumArt: UIViewControllerRepresentable { let url: URL? let size: CGFloat let isPlaying: Bool @Environment(\.accessibilityReduceMotion) private var reduceMotion @Environment(\.offlineOnly) private var offlineOnly func makeCoordinator() -> Coordinator { Coordinator() } func makeUIViewController(context: Context) -> UIHostingController { let controller = UIHostingController(rootView: artwork) controller.view.backgroundColor = .clear controller.view.isOpaque = false controller.view.isUserInteractionEnabled = false context.coordinator.attach(to: controller.view.layer) context.coordinator.artworkURL = url context.coordinator.artworkSize = size context.coordinator.offlineOnly = offlineOnly context.coordinator.setPlayback(isPlaying: isPlaying, reduceMotion: reduceMotion) return controller } func updateUIViewController(_ controller: UIHostingController, context: Context) { let coordinator = context.coordinator if coordinator.artworkURL != url || coordinator.artworkSize != size || coordinator.offlineOnly != offlineOnly { controller.rootView = artwork coordinator.artworkURL = url coordinator.artworkSize = size coordinator.offlineOnly = offlineOnly } coordinator.setPlayback(isPlaying: isPlaying, reduceMotion: reduceMotion) } func sizeThatFits( _ proposal: ProposedViewSize, uiViewController: UIHostingController, context: Context ) -> CGSize? { CGSize(width: size, height: size) } static func dismantleUIViewController( _ controller: UIHostingController, coordinator: Coordinator ) { coordinator.stop() } private var artwork: AnyView { AnyView( ArtworkView(url: url, size: size, cornerRadius: size / 2) .environment(\.offlineOnly, offlineOnly) .clipShape(Circle()) .frame(width: size, height: size) ) } final class Coordinator { var artworkURL: URL? var artworkSize: CGFloat = 0 var offlineOnly = false private enum Motion { case stopped case ramp(startedAt: CFTimeInterval, duration: CFTimeInterval, from: Double, to: Double) case cruising } private static let animationKey = "vinylRotation" private let rotationPeriod: CFTimeInterval = 7.2 private let rampDuration: CFTimeInterval = 1.6 private weak var layer: CALayer? private var motion: Motion = .stopped private var requestedPlaying = false private var reducedMotion = false private var generation = 0 private var cruisingSpeed: Double { 2 * .pi / rotationPeriod } func attach(to layer: CALayer) { self.layer = layer } func setPlayback(isPlaying: Bool, reduceMotion: Bool) { if reduceMotion { if !reducedMotion { stopImmediately() } reducedMotion = true requestedPlaying = false return } reducedMotion = false guard isPlaying != requestedPlaying else { return } requestedPlaying = isPlaying transition(toPlaying: isPlaying) } func stop() { generation += 1 layer?.removeAnimation(forKey: Self.animationKey) layer = nil } private func stopImmediately() { let angle = displayedAngle() generation += 1 freeze(at: angle) motion = .stopped } private func transition(toPlaying active: Bool) { let now = CACurrentMediaTime() let angle = displayedAngle() let speed = currentSpeed(at: now) generation += 1 freeze(at: angle) if active { ramp(from: angle, speed: speed, to: cruisingSpeed, at: now) } else if speed > 0.001 { ramp(from: angle, speed: speed, to: 0, at: now) } else { motion = .stopped } } private func displayedAngle() -> Double { guard let transform = (layer?.presentation() ?? layer)?.transform else { return 0 } return atan2(transform.m12, transform.m11) } private func currentSpeed(at time: CFTimeInterval) -> Double { switch motion { case .stopped: return 0 case .cruising: return cruisingSpeed case .ramp(let startedAt, let duration, let from, let to): let progress = min(max((time - startedAt) / duration, 0), 1) return from + (to - from) * progress } } private func freeze(at angle: Double) { guard let layer else { return } CATransaction.begin() CATransaction.setDisableActions(true) layer.setValue(angle, forKeyPath: "transform.rotation.z") layer.removeAnimation(forKey: Self.animationKey) CATransaction.commit() } private func ramp( from angle: Double, speed initialSpeed: Double, to finalSpeed: Double, at time: CFTimeInterval ) { guard let layer else { return } let duration = rampDuration let finalAngle = angle + (initialSpeed + finalSpeed) * duration / 2 let steps = 60 let animation = CAKeyframeAnimation(keyPath: "transform.rotation.z") animation.values = (0...steps).map { step in let progress = Double(step) / Double(steps) let elapsed = duration * progress return NSNumber( value: angle + initialSpeed * elapsed + (finalSpeed - initialSpeed) * elapsed * progress / 2) } animation.keyTimes = (0...steps).map { NSNumber(value: Double($0) / Double(steps)) } animation.calculationMode = .linear animation.duration = duration motion = .ramp(startedAt: time, duration: duration, from: initialSpeed, to: finalSpeed) let rampGeneration = generation CATransaction.begin() CATransaction.setDisableActions(true) CATransaction.setCompletionBlock { [weak self] in Task { @MainActor [weak self] in self?.finishRamp(generation: rampGeneration, angle: finalAngle) } } layer.setValue(finalAngle, forKeyPath: "transform.rotation.z") layer.add(animation, forKey: Self.animationKey) CATransaction.commit() } private func finishRamp(generation completedGeneration: Int, angle: Double) { guard generation == completedGeneration else { return } if requestedPlaying { cruise(from: angle) } else { motion = .stopped } } private func cruise(from angle: Double) { guard let layer else { return } let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.fromValue = angle animation.toValue = angle + 2 * Double.pi animation.duration = rotationPeriod animation.repeatCount = .infinity animation.timingFunction = CAMediaTimingFunction(name: .linear) layer.add(animation, forKey: Self.animationKey) motion = .cruising } } }