import SwiftUI import UIKit /// Four colours sampled from the corners of a cover, already darkened. struct CoverPalette: Equatable { let topLeading: Color let topTrailing: Color let bottomLeading: Color let bottomTrailing: Color static let dark = CoverPalette( topLeading: Color(white: 0.09), topTrailing: Color(white: 0.06), bottomLeading: Color(white: 0.05), bottomTrailing: Color(white: 0.03) ) } /// Downloads artwork for the backdrop and the Now Playing card. /// /// Artwork in the interface goes through `AsyncImage`; this exists for the two /// places that need the bitmap itself. @MainActor final class ImageCache { static let shared = ImageCache() private var palettes: [URL: CoverPalette] = [:] private init() {} func image(for url: URL) async -> UIImage? { guard let (data, response) = try? await URLSession.shared.data(from: url) else { return nil } if let http = response as? HTTPURLResponse, !(200 ..< 300).contains(http.statusCode) { return nil } return UIImage(data: data) } func palette(for url: URL) async -> CoverPalette { if let hit = palettes[url] { return hit } guard let image = await image(for: url) else { return .dark } let palette = await Task.detached(priority: .utility) { Self.palette(from: image) }.value palettes[url] = palette if palettes.count > 40 { palettes.removeAll() } return palette } /// Squash the cover down to 2x2 and read the four pixels. A gradient built /// from those reads as an out-of-focus version of the artwork without /// drawing, blurring or stretching a single bitmap. nonisolated private static func palette(from image: UIImage) -> CoverPalette { let size = CGSize(width: 2, height: 2) var pixels = [UInt8](repeating: 0, count: 16) guard let space = CGColorSpace(name: CGColorSpace.sRGB), let context = CGContext( data: &pixels, width: 2, height: 2, bitsPerComponent: 8, bytesPerRow: 8, space: space, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue ), let cg = image.cgImage else { return .dark } context.interpolationQuality = .medium context.draw(cg, in: CGRect(origin: .zero, size: size)) func colour(_ index: Int) -> Color { let base = index * 4 return darkened( red: Double(pixels[base]) / 255, green: Double(pixels[base + 1]) / 255, blue: Double(pixels[base + 2]) / 255 ) } // CGContext origin is bottom-left, so rows come back flipped. return CoverPalette( topLeading: colour(2), topTrailing: colour(3), bottomLeading: colour(0), bottomTrailing: colour(1) ) } /// Pulls every colour down to a dark ceiling, so a mostly white sleeve does /// not turn the whole screen into a lightbox. nonisolated private static func darkened(red: Double, green: Double, blue: Double) -> Color { let luminance = 0.2126 * red + 0.7152 * green + 0.0722 * blue let ceiling = 0.20 let scale = luminance > 0.001 ? min(1, ceiling / luminance) : 1 return Color( .sRGB, red: red * scale, green: green * scale, blue: blue * scale, opacity: 1 ) } } /// The ambient wash behind the player, artist and album screens. /// /// A gradient rather than a blurred bitmap: no decode, no stretching, and a /// single fill for the compositor. struct BlurredBackdrop: View { let url: URL? @State private var palette: CoverPalette = .dark var body: some View { ZStack { Color.black LinearGradient( stops: [ .init(color: palette.topLeading, location: 0), .init(color: palette.topTrailing, location: 0.38), .init(color: palette.bottomLeading, location: 0.72), .init(color: palette.bottomTrailing, location: 1), ], startPoint: .topLeading, endPoint: .bottomTrailing ) } .ignoresSafeArea() .animation(.easeInOut(duration: 0.6), value: palette) .task(id: url) { guard let url else { palette = .dark return } let loaded = await ImageCache.shared.palette(for: url) guard !Task.isCancelled else { return } palette = loaded } } }