### Generate and open the demo app with make demo-app Source: https://github.com/2dubu/palettekit/blob/main/Examples/PaletteKitDemo/README.md Run from the repo root to generate PaletteKitDemo.xcodeproj from project.yml and open it in Xcode. The first run triggers make setup, which installs xcodegen via Homebrew if not already present; subsequent runs skip that step. ```bash make demo-app ``` -------------------------------- ### Build PaletteKitDemo with make Source: https://github.com/2dubu/palettekit/blob/main/README.md Build and open the PaletteKitDemo SwiftUI app. Run `make setup` once to install xcodegen via Homebrew if missing, then `make demo-app` to generate PaletteKitDemo.xcodeproj and open it in Xcode. ```bash make setup # one-time: installs xcodegen via Homebrew if missing make demo-app # generate PaletteKitDemo.xcodeproj and open it in Xcode ``` -------------------------------- ### Getting Started with PaletteKit Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/PaletteKit.md Shows the basic usage of PaletteExtractor to extract a dominant color, a palette, and swatches from different image sources. The API is async-only and Sendable. ```swift import PaletteKit let extractor = PaletteExtractor() let color = try await extractor.dominantColor(from: .cgImage(image)) print(color?.hex ?? "no dominant color") let palette = try await extractor.palette(from: .url(fileURL)) palette.forEach { print($0.hex, $0.proportion) } let swatches = try await extractor.swatches(from: .data(data)) swatches.vibrant?.color.hex ``` -------------------------------- ### Resolve dependencies and build the package Source: https://github.com/2dubu/palettekit/blob/main/CONTRIBUTING.md Resolves package dependencies and builds the package in debug configuration. Use this before running tests or when starting development. ```sh swift package resolve swift build -c debug ``` -------------------------------- ### Use palette and swatches in UIKit with UIColor(_:) Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/GettingStarted.md UIKit example: extracts a palette, classifies it, and applies the vibrant swatch to a view and label. Also shows direct Core Graphics drawing using the dominant color's cgColor without a UIColor hop. ```swift let palette = try await extractor.palette( from: .data(imageData), options: ExtractionOptions(colorCount: 16) ) let swatches = SwatchClassifier().classify(palette: palette) if let vibrant = swatches.vibrant { view.backgroundColor = UIColor(vibrant.color) label.textColor = UIColor(vibrant.titleTextColor) } // For Core Graphics drawing (CALayer, CGContext) — direct, no UIColor hop: layer.backgroundColor = palette.dominant?.cgColor ``` -------------------------------- ### Measure per-stage timings with collectTimings Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/PerformanceTuning.md Enables collectTimings to get per-stage Duration values on the returned Palette, printing decode, quantize, and engine timings without using Instruments. ```swift let palette = try await extractor.palette( from: .url(url), options: ExtractionOptions(collectTimings: true) ) print("decode:", palette.timings?.decode ?? .zero) print("quantize:", palette.timings?.quantize ?? .zero) print("engine:", palette.timings?.quantizerUsed ?? "unknown") ``` -------------------------------- ### Use SwatchMap convenience lookups with fallback Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/GettingStarted.md Uses SwatchMap convenience helpers to get title, body, and accent colors with fallbacks. These helpers work on SwatchMap? (e.g., PaletteGraphic.swatches) so optional callsites do not need an extra unwrap. ```swift let titleColor = swatches.titleTextColor(for: .vibrant, fallback: .black) let bodyColor = swatches.bodyTextColor(for: .muted, fallback: .black) let accent = swatches.color(for: .lightVibrant, fallback: palette.dominant ?? .black) ``` -------------------------------- ### Extract palette from CGImage Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/ImageColorExtraction.md Calls palette(from:options:) with ExtractionOptions(colorCount: 8) to get a Palette sorted by population. The dominant property is the most populous color. ```swift import CoreGraphics import PaletteKit func imagePalette(from image: CGImage) async throws -> Palette { try await PaletteExtractor().palette( from: .cgImage(image), options: ExtractionOptions(colorCount: 8) ) } ``` -------------------------------- ### Install PaletteKit via Swift Package Manager Source: https://github.com/2dubu/palettekit/blob/main/README.md Add PaletteKit as a Swift Package Manager dependency. Requires minimum iOS 17 and Xcode 16+. For on-device naming and summaries, also add the optional PaletteKitInsights product (iOS 26+). ```swift // Package.swift dependencies: [ .package(url: "https://github.com/2dubu/PaletteKit", from: "2.1.1"), ] ``` -------------------------------- ### Use palette and swatches in SwiftUI with ShapeStyle Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/GettingStarted.md SwiftUI example: extracts a palette, classifies it with SwatchClassifier, and uses the dominant color and vibrant swatch in a VStack. PaletteColor conforms to ShapeStyle (iOS 17+), so it works directly with .fill, .foregroundStyle, .background, .tint, and .border. Internally resolve(in:) produces a Color.Resolved tagged sRGB. ```swift let palette = try await extractor.palette( from: .data(imageData), options: ExtractionOptions(colorCount: 16) ) let swatches = SwatchClassifier().classify(palette: palette) VStack { Rectangle() .fill(palette.dominant ?? .black) .frame(height: 80) if let vibrant = swatches.vibrant { Text("Vibrant") .foregroundStyle(vibrant.titleTextColor) .padding() .background(vibrant.color) } } ``` -------------------------------- ### Get semantic swatches with extractor.swatches(from:) Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/GettingStarted.md Extracts semantic swatches from image data and uses the vibrant swatch to set UIKit colors. Each Swatch also exposes titleTextColor and bodyTextColor as recommended black or white foreground colors; validate the final combination against your accessibility target. ```swift let swatches = try await extractor.swatches(from: .data(imageData)) if let vibrant = swatches.vibrant { view.backgroundColor = UIColor(vibrant.color) label.textColor = UIColor(vibrant.titleTextColor) } ``` -------------------------------- ### Extract dominant color from UIImage Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/ImageColorExtraction.md Converts a UIImage to a CGImage and uses PaletteExtractor.dominantColor(from:options:) to get a PaletteColor?. Returns nil if the UIImage has no CGImage backing store. ```swift import PaletteKit import UIKit func dominantColor(in image: UIImage) async throws -> PaletteColor? { guard let cgImage = image.cgImage else { return nil } return try await PaletteExtractor().dominantColor(from: .cgImage(cgImage)) } ``` -------------------------------- ### Use PaletteColor as ShapeStyle in SwiftUI Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/Options.md Demonstrates SwiftUI integration: PaletteColor conforms to ShapeStyle (iOS 17+), so it can be used directly with ShapeStyle-accepting modifiers. The example extracts a palette, classifies swatches, and applies colors to a Rectangle and Text. ```swift let palette = try await extractor.palette( from: .data(imageData), options: ExtractionOptions(colorCount: 16) ) let swatches = SwatchClassifier().classify(palette: palette) Rectangle() .fill(palette.dominant ?? .black) if let vibrant = swatches.vibrant { Text("Hello") .foregroundStyle(vibrant.titleTextColor) } ``` -------------------------------- ### Usage Tips Source: https://github.com/2dubu/palettekit/blob/main/README.md Usage tips for different source types and color space behavior. ```APIDOC ## Use `.data` for in-memory bytes ### Description The `.data` path skips file-system overhead. Prefer it for HEIC/JPEG bytes already in memory or fetched over the network. ### Example ```swift let palette = try await extractor.palette(from: .data(imageData)) ``` ``` ```APIDOC ## Use `.url` for on-disk files ### Description The `.url` path lets the decoder mmap the file directly. Use it for on-disk files. ### Example ```swift let palette = try await extractor.palette(from: .url(fileURL)) ``` ``` ```APIDOC ## Color space output ### Description Palette colors are kept in the source color space (`CGImage.colorSpace`). OKLCH is used only internally. ### Example ```swift let palette = try await extractor.palette(from: .url(hdrPhotoURL)) palette.colorSpaceUsed // .displayP3 on iPhone HEIC, .sRGB elsewhere ``` ``` -------------------------------- ### Compare CPU and Metal quantizer options Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/PerformanceTuning.md Creates two ExtractionOptions instances to compare CPU and Metal quantizers with highest quality and no downsampling. Use these explicit overrides with collectTimings to measure performance on your own workloads. ```swift let cpu = ExtractionOptions( quality: .highest, downsample: .disabled, quantizer: .cpu ) let metal = ExtractionOptions( quality: .highest, downsample: .disabled, quantizer: .metal ) ``` -------------------------------- ### Basic AsyncPaletteGraphic usage Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/AsyncLoading.md Creates an AsyncPaletteGraphic from a URL, showing a gray placeholder during loading and on failure. The view is framed and clipped to a rounded rectangle. ```swift AsyncPaletteGraphic(image: .url(url)) { Color.gray.opacity(0.1) // placeholder during loading and on failure } .frame(width: 320, height: 320) .clipShape(RoundedRectangle(cornerRadius: 24)) ``` -------------------------------- ### Choose accuracy vs speed with ExtractionOptions Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/Options.md Shows four accuracy-versus-speed configurations: default CPU MMCQ, full-sampling CPU, full-sampling Metal, and a custom quantizer. .auto always picks CPU; on non-Metal targets .metal falls back to CPU, and on Metal-capable targets device/queue/shader failures surface as errors. ```swift // Default — CPU MMCQ with up to about 1M raster pixels: ExtractionOptions() // == .auto, default downsample // Every source pixel, CPU MMCQ: ExtractionOptions(quality: .highest, downsample: .disabled, quantizer: .cpu) // The same full-sampling workload with a Metal histogram: ExtractionOptions(quality: .highest, downsample: .disabled, quantizer: .metal) // Custom quantizer: ExtractionOptions(quantizer: .custom(MyQuantizer())) ``` -------------------------------- ### Configure quality and size with ExtractionOptions Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/Options.md Configure color count, stride-based quality, and automatic downsampling. The comment notes that .stride(5) samples every 5th pixel and .automatic(maxPixels:) uses a CGImageSource thumbnail. ```swift ExtractionOptions( colorCount: 6, quality: .stride(5), // every 5th pixel downsample: .automatic(maxPixels: 500_000) // CGImageSource thumbnail ) ``` -------------------------------- ### Configure quantizer and downsampling Source: https://github.com/2dubu/palettekit/blob/main/README.md Shows three ways to configure the quantizer and downsampling. The default uses CPU with auto-downsample to about 1M pixels. For maximum accuracy, disable downsampling and use the CPU quantizer. For large inputs (≥4MP raw), disable downsampling and use the Metal quantizer for a ~5-10% speedup. ```swift // Default — CPU with auto-downsample to ~1M pixels: try await extractor.palette(from: source) // Maximum accuracy — every pixel, CPU MMCQ: try await extractor.palette(from: source, options: ExtractionOptions(downsample: .disabled, quantizer: .cpu)) // Large-input accuracy + Metal (≥4MP raw): try await extractor.palette(from: source, options: ExtractionOptions(downsample: .disabled, quantizer: .metal)) ``` -------------------------------- ### Set color space with ExtractionOptions Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/Options.md Choose the color space for quantization. .oklch is the default and converts sampled pixels to OKLCH; .sRGB uses direct RGB-space MMCQ. Display P3 input is auto-detected and converted accordingly. ```swift ExtractionOptions(colorSpace: .oklch) // default ``` ```swift ExtractionOptions(colorSpace: .sRGB) // direct RGB-space MMCQ ``` -------------------------------- ### Phase-based AsyncPaletteGraphic usage Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/AsyncLoading.md Uses the phase-based initializer that mirrors AsyncImage. Handles .empty, .loading, .success, and .failure phases. The phase init takes no onFailure callback; observe .failure directly in the closure. ```swift AsyncPaletteGraphic(image: .url(url)) { phase in switch phase { case .empty, .loading: ProgressView() case .success(let palette, let swatches, _): HStack { PaletteGraphic(palette: palette, swatches: swatches, configuration: .init()) .frame(width: 200, height: 200) VStack(alignment: .leading) { ForEach(palette.colors.prefix(5), id: \.hex) { color in Circle().fill(Color(color)).frame(width: 16, height: 16) } } } case .failure(let error): Text(error.localizedDescription).foregroundStyle(.red) } } ``` -------------------------------- ### Load palette from local URL Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/ImageColorExtraction.md Uses ImageSource.url(_:) to extract a palette from an image file on disk. ```swift let palette = try await PaletteExtractor().palette(from: .url(fileURL)) ``` -------------------------------- ### Call SwatchMap helpers on optional SwatchMap? Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/GettingStarted.md Shows that the same SwatchMap convenience calls work on an optional SwatchMap? without requiring an extra unwrap. The existing if let pattern continues to work; pick whichever reads better at the callsite. ```swift // SwatchMap? — no extra `?` required let textColor = swatches.titleTextColor(for: .vibrant, fallback: .black) ``` -------------------------------- ### AsyncPaletteGraphic from URL Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/Card.md SwiftUI async loading of a palette graphic from a URL. Provide a placeholder view while the image loads. ```swift AsyncPaletteGraphic(image: .url(url)) { Color.gray.opacity(0.1) } .frame(width: 320, height: 320) .clipShape(RoundedRectangle(cornerRadius: 24)) ``` -------------------------------- ### Run macOS CI unit test suites Source: https://github.com/2dubu/palettekit/blob/main/CONTRIBUTING.md Runs the unit test suites used by the macOS CI job. Use this to verify changes before requesting review. ```sh swift test --filter PaletteKitTests --filter PaletteKitInsightsTests ``` -------------------------------- ### Timings: ExtractionOptions(collectTimings: true) Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/Options.md Enable per-stage timing collection by setting collectTimings: true in ExtractionOptions. The resulting palette.timings exposes decode, quantize, and quantizerUsed properties; quantizerUsed reports either "MMCQ-CPU" or "MMCQ-Metal". Leave collectTimings false in production when timings are not needed. ```swift let palette = try await extractor.palette( from: source, options: ExtractionOptions(collectTimings: true) ) palette.timings?.decode palette.timings?.quantize palette.timings?.quantizerUsed // "MMCQ-CPU" or "MMCQ-Metal" ``` -------------------------------- ### Configure filtering with ExtractionOptions Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/Options.md Set filtering thresholds and fallback behavior. With .relax, if all pixels are filtered out, the filter chain retries with looser settings and finally returns the image average; use .fail to throw PaletteError.allPixelsFiltered instead. ```swift ExtractionOptions( ignoreWhite: true, whiteThreshold: 240, alphaThreshold: 50, minSaturation: 0.1, fallbackStrategy: .relax ) ``` -------------------------------- ### AsyncPaletteGraphic with explicit cache and cacheKey Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/AsyncLoading.md Passes an explicit cacheKey to enable caching for .data(_:) or .cgImage(_:) sources. Uses the shared cache by default. ```swift AsyncPaletteGraphic( image: .data(data), cache: .shared, cacheKey: AnyHashable(itemId) ) { Color.clear } ``` -------------------------------- ### ExtractionOptions Source: https://github.com/2dubu/palettekit/blob/main/README.md Configuration options for palette extraction: color count, quality, color space, downsampling, and quantizer. ```APIDOC ## Configure extraction options ### Description `ExtractionOptions` controls color count, sampling quality, color space, downsampling, and the quantizer algorithm. ### Fields - **colorCount** (`Int`) - Optional - Number of colors in the palette. - **quality** (`SamplingQuality`) - Optional - Sampling quality. - **colorSpace** (`CGColorSpace`) - Optional - Output color space. - **downsample** (`DownsampleMode`) - Optional - Downsampling mode; `.disabled` disables auto-downsample. - **quantizer** (`Quantizer`) - Optional - Quantizer algorithm; `.auto`, `.cpu`, or `.metal`. ### Example ```swift let options = ExtractionOptions(downsample: .disabled, quantizer: .cpu) ``` ``` -------------------------------- ### Load palette graphic asynchronously with AsyncPaletteGraphic Source: https://github.com/2dubu/palettekit/blob/main/README.md Load a palette graphic asynchronously with a placeholder shown during loading and on failure. The UIKit pair is AsyncPaletteGraphicView. Both share a process-wide PaletteCache.shared. ```swift import PaletteKit import SwiftUI AsyncPaletteGraphic(image: .url(url)) { Color.gray.opacity(0.1) // shown during loading and on failure } .frame(width: 320, height: 320) .clipShape(RoundedRectangle(cornerRadius: 24)) ``` -------------------------------- ### Check palette color space Source: https://github.com/2dubu/palettekit/blob/main/README.md Shows how to extract a palette from a URL and check the color space used. The palette retains the source color space, so Display P3 input yields Display P3 output. The comment notes the expected color space on an iPhone HEIC versus elsewhere. ```swift let palette = try await extractor.palette(from: .url(hdrPhotoURL)) palette.colorSpaceUsed // .displayP3 on an iPhone HEIC, .sRGB elsewhere ``` -------------------------------- ### Load palette from remote URL via Data Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/ImageColorExtraction.md Downloads image data with URLSession and passes it as Data to PaletteExtractor.palette(from:options:). Keeps networking policy outside the library. ```swift let (data, _) = try await URLSession.shared.data(from: remoteURL) let palette = try await PaletteExtractor().palette(from: .data(data)) ``` -------------------------------- ### Configure downsample for decoding Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/PerformanceTuning.md Sets the maximum pixel edge for ImageIO thumbnail decoding to 1024 pixels, reducing decode cost when thumbnail creation succeeds. ```swift ExtractionOptions(downsample: .maxEdge(1024)) ``` -------------------------------- ### Generate palette insights with PaletteInsightsGenerator Source: https://github.com/2dubu/palettekit/blob/main/README.md Generate a palette name and one-line summary using the on-device FoundationModels model (no network). Requires iOS 26+ and the PaletteKitInsights module. Check isAvailable and supportsLocale() before calling insights(for:guidance:). ```swift import PaletteKit import PaletteKitInsights let palette = try await PaletteExtractor().palette(from: image) let generator = PaletteInsightsGenerator() guard generator.isAvailable, generator.supportsLocale() else { return } // fallback otherwise let insights = try await generator.insights( for: palette, guidance: "warm and nostalgic" // optional ) print(insights.name) // e.g. "Faded Coastline" print(insights.summary) // one sentence, in the device language ``` -------------------------------- ### Render swatches in UIKit Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/ImageColorExtraction.md Extracts swatches from Data and uses the vibrant swatch to set a view's background and label text color via UIColor initializer. ```swift let swatches = try await PaletteExtractor().swatches(from: .data(imageData)) if let vibrant = swatches.vibrant { view.backgroundColor = UIColor(vibrant.color) label.textColor = UIColor(vibrant.titleTextColor) } ``` -------------------------------- ### Tune extraction options for large photos Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/ImageColorExtraction.md Configures ExtractionOptions with quality .stride(5) and downsample .automatic(maxPixels: 500_000) to adjust detail vs. work for large images. ```swift let options = ExtractionOptions( quality: .stride(5), downsample: .automatic(maxPixels: 500_000) ) let palette = try await PaletteExtractor().palette( from: .data(imageData), options: options ) ``` -------------------------------- ### Extract palette with timings Source: https://github.com/2dubu/palettekit/blob/main/README.md Extract a palette with timing collection enabled. Access per-stage durations (decode, sample, quantize) and the total, plus the quantizer used ("MMCQ-CPU" or "MMCQ-Metal"). Traces are annotated via os_signpost (com.paletteKit / pointsOfInterest) for the "Points of Interest" template. ```swift let palette = try await extractor.palette( from: .url(url), options: ExtractionOptions(collectTimings: true) ) palette.timings?.decode // Duration palette.timings?.sample // Duration palette.timings?.quantize // Duration palette.timings?.total // Duration palette.timings?.quantizerUsed // "MMCQ-CPU" or "MMCQ-Metal" ``` -------------------------------- ### AsyncPaletteGraphic with onFailure callback Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/AsyncLoading.md Surfaces errors via the optional onFailure callback. The placeholder remains visible. ```swift AsyncPaletteGraphic(image: .url(url), onFailure: { Logger.shared.error($0) }) { Color.gray.opacity(0.1) } ``` -------------------------------- ### Extractor API methods Source: https://github.com/2dubu/palettekit/blob/main/README.md Lists the three main extraction methods on the extractor object. Each returns an optional PaletteColor, a Palette, or a SwatchMap respectively. Use these as the primary entry points for color extraction. ```swift extractor.dominantColor(from:) // PaletteColor? extractor.palette(from:) // Palette extractor.swatches(from:) // SwatchMap ``` -------------------------------- ### Extract palette and swatches in UIKit Source: https://github.com/2dubu/palettekit/blob/main/README.md Extract a palette and swatches from image data and apply them in UIKit. Convert colors to UIColor for view background and label text color. ```swift import PaletteKit import UIKit let extractor = PaletteExtractor() let palette = try await extractor.palette(from: .data(imageData)) let swatches = try await extractor.swatches(from: .data(imageData)) view.backgroundColor = UIColor(palette.dominant ?? .black) label.textColor = UIColor(swatches.titleTextColor(for: .vibrant, fallback: .black)) ``` -------------------------------- ### Inspect colorSpaceUsed to detect Display P3 source Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/ColorSpaces.md Checks the detected source color space after extraction with the default OKLCH mode. In direct .sRGB or .displayP3 modes, colorSpaceUsed records the selected mode instead of the detected source. ```swift switch palette.colorSpaceUsed { case .displayP3: print("Display P3 source") case .sRGB: print("sRGB source") case .oklch: print("Custom OKLCH metadata") } ``` -------------------------------- ### Extract a palette from a URL with ExtractionOptions Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/GettingStarted.md Extracts a palette from a remote image URL with a custom colorCount of 8. The returned palette is a Collection sorted by population, and its colorSpaceUsed records the detected or selected color space. ```swift let palette = try await extractor.palette( from: .url(imageURL), options: ExtractionOptions(colorCount: 8) ) for entry in palette { print(entry.hex, entry.proportion) } ``` -------------------------------- ### Setting AsyncPaletteGraphicView transition in UIKit Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/AsyncLoading.md Sets the transition property directly on an AsyncPaletteGraphicView instance in UIKit. ```swift asyncView.transition = .extraSlow ``` -------------------------------- ### Generate a palette graphic with PaletteGraphic Source: https://github.com/2dubu/palettekit/blob/main/README.md Generate a static palette graphic with a custom configuration. For UIKit, use PaletteGraphicView (UIView) or PaletteGraphic.makeImage(size:scale:) / PaletteGraphicView.snapshotImage(scale:) for a static UIImage. ```swift import PaletteKit import SwiftUI let configuration = PaletteGraphic.Configuration( direction: .linear, colorCount: .three, swatchStrategy: .vibrant, grain: .standard ) PaletteGraphic(palette: palette, swatches: swatches, configuration: configuration) .frame(width: 320, height: 320) .clipShape(RoundedRectangle(cornerRadius: 24)) ``` -------------------------------- ### Create semantic swatches with PaletteExtractor.swatches Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/ChoosingAnExtractionResult.md Use when the interface needs role-based color choices. The swatch classifier looks for up to six roles: vibrant, muted, dark vibrant, dark muted, light vibrant, and light muted. Each role is optional because an image may not contain a suitable unused color in that role's lightness and chroma range. The swatch method raises a smaller requested color count to 16 so the classifier has enough candidates. ```swift let swatches = try await PaletteExtractor().swatches(from: .data(imageData)) let background = swatches.color( for: .vibrant, fallback: .black ) ``` -------------------------------- ### Synchronous palette extraction with PaletteExtractor Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/AsyncLoading.md Shows the synchronous v1.4 PaletteGraphic approach, which requires the caller to extract a Palette first using PaletteExtractor().palette(from: .url(url)). ```swift let palette = try await PaletteExtractor().palette(from: .url(url)) PaletteGraphic(palette: palette, swatches: nil, configuration: .init()) ``` -------------------------------- ### PaletteKit API Source: https://github.com/2dubu/palettekit/blob/main/README.md Core extraction methods for PaletteKit: dominant color, full palette, and swatch map. ```APIDOC # SDK: PaletteKit A Swift framework to extract color palettes from images. ``` ```APIDOC ## Extract default color ### Description Returns the dominant color of an image source. The source can be a CGImage, Data, or URL. ### Method `dominantColor(from:)` ### Parameters - **source** (`ImageSource`) - Required - The image source: `.cgImage`, `.data`, or `.url`. ### Returns `PaletteColor?` - The dominant color or `nil` if extraction fails. ### Example ```swift let color = extractor.dominantColor(from: .url(imageURL)) ``` ``` ```APIDOC ## Extract full palette ### Description Asynchronously extracts a palette from a given image source. ### Method `palette(from:)` ### Parameters - **source** (`ImageSource`) - Required - The image source: `.cgImage`, `.data`, or `.url`. - **options** (`ExtractionOptions`) - Optional - Overrides for `colorCount`, `quality`, `colorSpace`, `downsample`, and `quantizer`. ### Returns `Palette` - The extracted palette. ### Example ```swift let palette = try await extractor.palette(from: .url(imageURL)) ``` ``` ```APIDOC ## Extract swatches ### Description Returns a map of color-to-count swatches for an image source. ### Method `swatches(from:)` ### Parameters - **source** (`ImageSource`) - Required - The image source: `.cgImage`, `.data`, or `.url`. ### Returns `SwatchMap` - The swatch map. ### Example ```swift let swatches = extractor.swatches(from: .data(imageData)) ``` ``` -------------------------------- ### Extract palette and swatches in SwiftUI Source: https://github.com/2dubu/palettekit/blob/main/README.md Extract a palette and swatches from image data and apply them in SwiftUI. Use palette.dominant for a fill color and swatches.titleTextColor(for:fallback:) for text color. ```swift import PaletteKit import SwiftUI let extractor = PaletteExtractor() let palette = try await extractor.palette(from: .data(imageData)) let swatches = try await extractor.swatches(from: .data(imageData)) Rectangle() .fill(palette.dominant ?? .black) Text("Hello") .foregroundStyle(swatches.titleTextColor(for: .vibrant, fallback: .black)) ``` -------------------------------- ### Render palette in SwiftUI Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/ImageColorExtraction.md Uses PaletteColor's ShapeStyle conformance to fill rectangles in an HStack, displaying the first five colors of a Palette. ```swift import PaletteKit import SwiftUI struct PaletteStrip: View { let palette: Palette var body: some View { HStack(spacing: 0) { ForEach(Array(palette.prefix(5)), id: \.self) { color in Rectangle().fill(color) } } } } ``` -------------------------------- ### UIKit integration: UIColor(_:) and cgColor Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/Options.md Use the UIColor(_:) convenience initializer to convert a palette's dominant color for UIKit views. The optional chaining with ?? .black provides a fallback when no dominant color exists. For Core Graphics drawing, access the cgColor property directly to avoid a UIColor conversion. ```swift let palette = try await extractor.palette(from: .data(imageData)) let label = UILabel() label.textColor = UIColor(palette.dominant ?? .black) // For Core Graphics drawing (CALayer, CGContext) — direct, no UIColor hop: layer.backgroundColor = palette.dominant?.cgColor ``` -------------------------------- ### Generate UIImage from PaletteMeshGraphic Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/Card.md Generate a static UIImage from a PaletteMeshGraphic. Must be called from the main actor because it uses SwiftUI's ImageRenderer. ```swift let image: UIImage? = PaletteMeshGraphic(palette: palette) .makeImage(size: CGSize(width: 1080, height: 1080)) ``` -------------------------------- ### Animate a palette graphic with AnimatedPaletteGraphic Source: https://github.com/2dubu/palettekit/blob/main/README.md Render a slowly morphing 'living gradient' with organic, non-periodic motion. It fills its frame; clip to any shape. UIKit pair is AnimatedPaletteGraphicView. Both honor Reduce Motion and Low Power Mode (hold a static frame) and pause while off-screen. ```swift AnimatedPaletteGraphic( palette: palette, configuration: .init( colorCount: .three, // .two ... .five speed: .regular, // .slow / .regular / .fast isAnimated: true ) ) .frame(width: 320, height: 420) .clipShape(RoundedRectangle(cornerRadius: 24)) ``` -------------------------------- ### UIKit PaletteGraphicView with Auto Layout Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/Card.md UIKit view using PaletteGraphicView with Auto Layout constraints. Update configuration or palette at runtime; the view re-renders on the next layout pass. ```swift import PaletteKit import UIKit let view = PaletteGraphicView( palette: palette, swatches: swatches, configuration: .init(direction: .linear, colorCount: .three) ) view.translatesAutoresizingMaskIntoConstraints = false container.addSubview(view) NSLayoutConstraint.activate([ view.widthAnchor.constraint(equalToConstant: 320), view.heightAnchor.constraint(equalToConstant: 320), view.centerXAnchor.constraint(equalTo: container.centerXAnchor), view.centerYAnchor.constraint(equalTo: container.centerYAnchor) ]) // Update at runtime — auto re-renders on the next layout pass. view.configuration.colorCount = .four view.palette = newPalette ``` -------------------------------- ### Extract dominant color with PaletteExtractor.dominantColor(from:) Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/GettingStarted.md Creates a PaletteExtractor and defines an async function that extracts the dominant color from a CGImage. The default colorCount is 10, and values below the valid palette range are normalized to 5 for this convenience method. The returned PaletteColor carries hex, hsl, oklch, contrast, and textColor without extra calls. ```swift import PaletteKit import CoreGraphics let extractor = PaletteExtractor() func extractDominant(cgImage: CGImage) async throws -> PaletteColor? { try await extractor.dominantColor(from: .cgImage(cgImage)) } ``` -------------------------------- ### Generate UIImage from PaletteGraphic Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/Card.md Generate a static UIImage from a PaletteGraphic for sharing or caching. Call makeImage(size:scale:) with the desired pixel dimensions. ```swift let image: UIImage? = PaletteGraphic(palette: palette, swatches: swatches) .makeImage(size: CGSize(width: 1080, height: 1080)) ``` -------------------------------- ### Extract dominant color with PaletteExtractor Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/FAQ.md Use this async call to extract the dominant color from a CGImage. The ImageSource can be .cgImage, .data, or .url. Requires Swift concurrency and a valid image source. ```swift let color = try await PaletteExtractor().dominantColor( from: .cgImage(cgImage) ) ``` -------------------------------- ### Reuse one extraction with SwatchClassifier.classify Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/ChoosingAnExtractionResult.md Use when an interface needs both a Palette and a SwatchMap. Extract at least 16 candidates and classify that palette directly to avoid decoding and quantizing the same image twice. ```swift let palette = try await PaletteExtractor().palette( from: .data(imageData), options: ExtractionOptions(colorCount: 16) ) let swatches = SwatchClassifier().classify(palette: palette) ``` -------------------------------- ### Build ranked palette with PaletteExtractor.palette Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/ChoosingAnExtractionResult.md Use when the interface needs several colors or population data. Palette colors are sorted by population. Palette/dominant returns the first color without running another extraction. ```swift let palette = try await PaletteExtractor().palette( from: .data(imageData), options: ExtractionOptions(colorCount: 8) ) for color in palette { print(color.hex, color.population, color.proportion) } ``` -------------------------------- ### SwiftUI PaletteGraphic view Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/Card.md SwiftUI view that renders a palette-driven gradient and grain graphic using PaletteGraphic. Configure direction, color count, swatch strategy, and grain style, then frame and clip the result. ```swift import PaletteKit import SwiftUI struct PaletteCard: View { let palette: Palette let swatches: SwatchMap? var body: some View { PaletteGraphic(palette: palette, swatches: swatches, configuration: .init( direction: .linear, linearStart: .bottomLeading, linearEnd: .topTrailing, colorCount: .three, swatchStrategy: .vibrant, grain: .standard )) .frame(width: 320, height: 320) .clipShape(RoundedRectangle(cornerRadius: 24)) } } ``` -------------------------------- ### Extract palette with OKLCH color space Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/ColorSpaces.md Extracts a palette from image data using the default OKLCH color space. The colorSpaceUsed property records the detected source space (sRGB or Display P3) when using this mode. ```swift let palette = try await PaletteExtractor().palette( from: .data(imageData), options: ExtractionOptions(colorSpace: .oklch) ) ``` -------------------------------- ### PaletteMeshGraphic SwiftUI view Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/Tutorials/Card.md SwiftUI mesh gradient graphic using PaletteMeshGraphic (iOS 18+). Does not take a SwatchMap; allocates slots proportional to palette color population. ```swift PaletteMeshGraphic(palette: palette) .frame(width: 320, height: 320) .clipShape(RoundedRectangle(cornerRadius: 24)) ``` -------------------------------- ### Extract dominant color with PaletteExtractor.dominantColor Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/ChoosingAnExtractionResult.md Use when the interface needs one representative color. The result is optional because a palette can be empty, including when a custom quantizer returns no colors. The method runs palette extraction with the supplied options and returns the most populous PaletteColor. ```swift let dominant = try await PaletteExtractor().dominantColor( from: .data(imageData) ) ``` -------------------------------- ### Setting asyncPaletteGraphicTransition modifier Source: https://github.com/2dubu/palettekit/blob/main/PaletteKit.docc/AsyncLoading.md Overrides the default cross-fade transition (0.20s) per subtree with the SwiftUI modifier .asyncPaletteGraphicTransition(.slow). ```swift NavigationStack { cardListView } .asyncPaletteGraphicTransition(.slow) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.