### Get Dominant Colors (Fast Extraction) Source: https://github.com/dendmitriev/dominantcolors/blob/main/README.md Use the .fair quality setting for a faster extraction of dominant colors, employing a pixelization algorithm for efficiency. ```swift let cgColors = try? DominantColors.dominantColors(image: cgImage, quality: .fair) ``` -------------------------------- ### Get Colors using K-Means Clustering Source: https://github.com/dendmitriev/dominantcolors/blob/main/README.md Find dominant colors using the k-means clustering algorithm. Adjust the quality and count parameters for desired results. ```swift let cgColors = try? DominantColors.kMeansClusteringColors(image: cgImage, quality: .fair, count: 10) ``` -------------------------------- ### Get Dominant Colors (Standard) Source: https://github.com/dendmitriev/dominantcolors/blob/main/README.md Quickly get dominant colors from CGImage, UIImage, or NSImage with standard settings. Specify the maximum number of colors to return. ```swift let dominantColors = try? image.dominantColors(max: 6) // Array of UIColor, NSColor or CGColor ``` ```swift let cgColors = try? DominantColors.dominantColors(image: cgImage, maxCount: 6) ``` ```swift let uiColors = try? DominantColors.dominantColors(uiImage: uiImage, maxCount: 6) ``` ```swift let nsColors = try? DominantColors.dominantColors(nsImage: nsImage, maxCount: 6) ``` ```swift let colorsResolved = try? DominantColors.dominantColorsResolved(image: cgImage) ``` -------------------------------- ### Get Dominant Colors (Custom Quality and Algorithm) Source: https://github.com/dendmitriev/dominantcolors/blob/main/README.md Achieve more accurate results by setting the quality to .best along with a specific algorithm. This is useful for detailed color analysis. ```swift let cgColors = try? DominantColors.dominantColors(image: cgImage, quality: .best, algorithm: .CIE76) ``` -------------------------------- ### Get Dominant Colors (With Options) Source: https://github.com/dendmitriev/dominantcolors/blob/main/README.md Extract dominant colors while applying specific options to exclude certain color types, such as black, gray, or white. ```swift let cgColors = try? DominantColors.dominantColors(image: cgImage, options: [.excludeBlack, .excludeGray, .excludeWhite]) ``` -------------------------------- ### Get Dominant Colors (Custom Algorithm) Source: https://github.com/dendmitriev/dominantcolors/blob/main/README.md Extract dominant colors using a specified color difference algorithm like CIE76. This allows for customization of color comparison. ```swift let cgColors = try? DominantColors.dominantColors(image: cgImage, algorithm: .CIE76) ``` -------------------------------- ### Get Average Colors Source: https://github.com/dendmitriev/dominantcolors/blob/main/README.md Calculate the average colors of an image by dividing it into horizontal segments. Specify the desired number of average colors to retrieve. ```swift let cgColors = try? DominantColors.averageColors(image: cgImage, count: 8) ``` -------------------------------- ### Get Dominant Colors (With Sorting) Source: https://github.com/dendmitriev/dominantcolors/blob/main/README.md Specify a sorting type, such as .darkness, to arrange the extracted dominant colors in a desired sequence. The default sorting is by frequency. ```swift let cgColors = try? DominantColors.dominantColors(image: cgImage, maxCount: 6, sorting: .darkness) ``` -------------------------------- ### Extract and Sort Dominant Colors in Swift Source: https://context7.com/dendmitriev/dominantcolors/llms.txt Demonstrates how to extract dominant colors from a CGImage and sort them by frequency, darkness, or lightness. ```swift import DominantColors let cgImage: CGImage = // ... your image // Access color frequencies directly (internal API) // The public API returns colors, but ColorFrequency contains: // - color: CGColor - The actual color // - frequency: CGFloat - Pixel count or percentage (0-1 after processing) // - shade: ColorShade - Category (red, orange, yellow, green, blue, purple, etc.) // - normal: CGFloat - Importance score based on frequency, lightness, and saturation // Example: dominant colors returns the color property from ColorFrequency let colors = try DominantColors.dominantColors(image: cgImage, maxCount: 6) // Colors are sorted by frequency by default // First color is most common in the image let mostCommonColor = colors.first // Sort by other criteria let darkToLight = try DominantColors.dominantColors( image: cgImage, sorting: .darkness ) let lightToDark = try DominantColors.dominantColors( image: cgImage, sorting: .lightness ) ``` -------------------------------- ### Generate Contrast Colors Source: https://github.com/dendmitriev/dominantcolors/blob/main/README.md Create contrast colors (background, primary, secondary) based on a given palette of dominant colors. This is useful for text and accompanying content. ```swift let dominantColors = try image.dominantColors() let contrastColors = ContrastColors(colors: dominantColors.map({ $0.cgColor })) let backgroundColor = contrastColors?.background let primaryColor = contrastColors?.primary let secondaryColor = contrastColors?.secondary ``` -------------------------------- ### Add DominantColors as a Swift Package Dependency Source: https://github.com/dendmitriev/dominantcolors/blob/main/README.md Include this dependency in your Package.swift file to integrate the library into your project. ```swift dependencies: [ .package(url: "https://github.com/DenDmitriev/DominantColors.git", .upToNextMajor(from: "1.2.0")) ] ``` -------------------------------- ### Generate Accessible Contrast Palettes in Swift Source: https://context7.com/dendmitriev/dominantcolors/llms.txt Creates color palettes that adhere to WCAG 2.0 guidelines for UI accessibility, providing background, primary, and secondary colors. ```swift import DominantColors // From extracted dominant colors let cgImage: CGImage = // ... your image let dominantColors = try DominantColors.dominantColors(image: cgImage, maxCount: 8) // Create contrast palette from unordered colors let palette = ContrastColors( colors: dominantColors, darkBackground: true, // Prefer dark background ignoreContrastRatio: false // Enforce WCAG contrast (recommended for text) ) if let palette = palette { let backgroundColor = palette.background // CGColor for background let titleColor = palette.primary // CGColor for main text let subtitleColor = palette.secondary // CGColor? for secondary text } // From ordered colors (first color is most important) let orderedPalette = ContrastColors( orderedColors: dominantColors, darkBackground: true, ignoreContrastRatio: false ) // iOS convenience method let uiImage = UIImage(named: "album_art")! if let contrastColors = uiImage.contrastColors(darkBackground: true) { // Use for music player UI view.backgroundColor = UIColor(cgColor: contrastColors.background) titleLabel.textColor = UIColor(cgColor: contrastColors.primary) artistLabel.textColor = contrastColors.secondary.map { UIColor(cgColor: $0) } } ``` -------------------------------- ### Compute Perceptual Color Differences in Swift Source: https://context7.com/dendmitriev/dominantcolors/llms.txt Calculates the visual difference between two colors using various CIE formulas, returning a result that can be categorized by similarity. ```swift import CoreGraphics import DominantColors let color1 = CGColor(red: 0.8, green: 0.2, blue: 0.2, alpha: 1.0) // Red let color2 = CGColor(red: 0.85, green: 0.25, blue: 0.15, alpha: 1.0) // Similar red // Calculate difference using CIE94 (default) let difference = color1.difference(from: color2) // Returns: ColorDifferenceResult switch difference { case .indentical(let value): print("Colors are identical: \(value)") // value == 0 case .similar(let value): print("Imperceptible difference: \(value)") // value <= 1.0 case .close(let value): print("Noticeable on close observation: \(value)") // value <= 2.0 case .near(let value): print("Noticeable at a glance: \(value)") // value <= 10.0 case .different(let value): print("Clearly different: \(value)") // value <= 50.0 case .far(let value): print("Very different/opposite: \(value)") // value > 50.0 } // Using different algorithms let euclidean = color1.difference(from: color2, using: .euclidean) let cie76 = color1.difference(from: color2, using: .CIE76) let cie94 = color1.difference(from: color2, using: .CIE94) let ciede2000 = color1.difference(from: color2, using: .CIEDE2000) // Most accurate let cmc = color1.difference(from: color2, using: .CMC) // Access the raw difference value let deltaE = difference.associatedValue // CGFloat ``` -------------------------------- ### Calculate Contrast Ratio Between Colors Source: https://context7.com/dendmitriev/dominantcolors/llms.txt Calculates the contrast ratio between two colors according to WCAG 2.0 guidelines. Use this to ensure text readability and accessibility in your designs. ```swift import CoreGraphics import DominantColors let textColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) // White let backgroundColor = CGColor(red: 0, green: 0, blue: 0, alpha: 1) // Black let contrastRatio = textColor.contrastRatio(with: backgroundColor) // Returns: ContrastRatioResult switch contrastRatio { case .acceptable(let ratio): // Ratio >= 4.5:1 - Good for all text sizes print("Accessible for all text: \(ratio):1") // 21.0:1 for black/white case .acceptableForLargeText(let ratio): // Ratio >= 3.0:1 but < 4.5:1 - Only for large text (18pt+ or 14pt+ bold) print("Only for large text: \(ratio):1") case .low(let ratio): // Ratio < 3.0:1 - Not accessible print("Insufficient contrast: \(ratio):1") } // Example with problematic colors let lightGray = CGColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1) let mediumGray = CGColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1) let lowContrast = lightGray.contrastRatio(with: mediumGray) // Returns: .low(1.47) - Not suitable for text ``` -------------------------------- ### Extract Dominant Colors from CGImage Source: https://context7.com/dendmitriev/dominantcolors/llms.txt Uses CIE color science to group similar colors and return a palette. Requires a CGImage input. ```swift import DominantColors // Basic usage with default settings let cgImage: CGImage = // ... load your image let dominantColors = try DominantColors.dominantColors(image: cgImage, maxCount: 6) // Returns: [CGColor] - Array of 6 dominant colors sorted by frequency // Advanced usage with all options let colors = try DominantColors.dominantColors( image: cgImage, quality: .high, // .low, .fair, .high, or .best algorithm: .CIEDE2000, // .euclidean, .CIE76, .CIE94, .CIEDE2000, or .CMC maxCount: 8, // Maximum colors to return options: [.excludeBlack, .excludeWhite, .excludeGray], // Filter options sorting: .darkness, // .frequency, .darkness, or .lightness deltaColors: 10, // Similarity threshold (lower = more shades) resultLog: true, // Print results to console timeLog: true // Print timing info ) // Output: DominantColor extract colors: [red, orange, yellow, green, blue, purple], count: 6, time: 0.045s ``` -------------------------------- ### Extract Dominant Colors with Quality Settings Source: https://context7.com/dendmitriev/dominantcolors/llms.txt Extracts dominant colors from an image using specified quality settings. Higher quality yields more accurate results but takes longer to process. ```swift import DominantColors // Quality levels and their characteristics: // .low - Fastest, ~1,000 pixel area, good for thumbnails // .fair - Balanced (default), ~10,000 pixel area // .high - More accurate, ~100,000 pixel area // .best - Most accurate, processes all pixels (slow for large images) let cgImage: CGImage = // ... your image // Fast extraction for real-time UI let quickColors = try DominantColors.dominantColors( image: cgImage, quality: .low, maxCount: 4 ) // Balanced for most use cases let balancedColors = try DominantColors.dominantColors( image: cgImage, quality: .fair, maxCount: 6 ) // High quality for final results let preciseColors = try DominantColors.dominantColors( image: cgImage, quality: .high, maxCount: 8 ) // Best quality for small images or when accuracy is critical let thumbnailImage: CGImage = // ... small image let bestColors = try DominantColors.dominantColors( image: thumbnailImage, quality: .best, maxCount: 10 ) ``` -------------------------------- ### Extract Colors via K-Means Clustering Source: https://context7.com/dendmitriev/dominantcolors/llms.txt Groups pixels into clusters using Core Image's CIKMeans filter to return average cluster colors. ```swift import DominantColors let cgImage: CGImage = // ... your image // Basic k-means extraction let clusterColors = try DominantColors.kMeansClusteringColors( image: cgImage, quality: .fair, count: 10, sorting: .frequency ) // Returns: [CGColor] - 10 cluster center colors // iOS with UIImage let uiImage = UIImage(named: "artwork")! let uiClusterColors = try DominantColors.kMeansClusteringColors( uiImage: uiImage, quality: .high, count: 8, sorting: .darkness ) // Returns: [UIColor] - Sorted from darkest to lightest // macOS with NSImage let nsImage = NSImage(named: "photo")! let nsClusterColors = try DominantColors.kMeansClusteringColors( nsImage: nsImage, count: 6 ) // Returns: [NSColor] ``` -------------------------------- ### K-Means Clustering Colors Source: https://context7.com/dendmitriev/dominantcolors/llms.txt Extracts dominant colors using the k-means clustering algorithm via Core Image's CIKMeans filter. ```APIDOC ## K-Means Clustering Colors ### Description Extracts dominant colors using the k-means clustering algorithm via Core Image's CIKMeans filter. This method groups pixels into clusters and returns the average color of each cluster. ### Method `DominantColors.kMeansClusteringColors(image:quality:count:sorting:)` for CGImage, `DominantColors.kMeansClusteringColors(uiImage:quality:count:sorting:)` for UIImage, `DominantColors.kMeansClusteringColors(nsImage:quality:count:sorting:)` for NSImage. ### Endpoint N/A (Swift Library Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import DominantColors let cgImage: CGImage = // ... your image // Basic k-means extraction for CGImage let clusterColors = try DominantColors.kMeansClusteringColors( image: cgImage, quality: .fair, count: 10, sorting: .frequency ) ``` ### Response #### Success Response (200) - **[CGColor]** or **[UIColor]** or **[NSColor]** - Array of cluster center colors. #### Response Example (CGColor) ```json [ "#FF5733", "#33FF57", "#3357FF" ] ``` ### iOS with UIImage Example ```swift import UIKit import DominantColors let uiImage = UIImage(named: "artwork")! let uiClusterColors = try DominantColors.kMeansClusteringColors( uiImage: uiImage, quality: .high, count: 8, sorting: .darkness ) // Returns: [UIColor] ``` ### macOS with NSImage Example ```swift import AppKit import DominantColors let nsImage = NSImage(named: "photo")! let nsClusterColors = try DominantColors.kMeansClusteringColors( nsImage: nsImage, count: 6 ) // Returns: [NSColor] ``` ``` -------------------------------- ### Extract Dominant Colors from UIImage Source: https://context7.com/dendmitriev/dominantcolors/llms.txt Convenience methods for iOS to extract colors directly from UIImage instances. ```swift import UIKit import DominantColors let uiImage = UIImage(named: "photo")! // Quick extraction with defaults let colors = try DominantColors.dominantColors(uiImage: uiImage, maxCount: 6) // Returns: [UIColor] - Array of UIColor instances // Using the UIImage extension for even simpler usage let dominantColors = try uiImage.dominantColors(max: 6, options: [.excludeWhite]) // Returns: [UIColor] // Full customization let customColors = try DominantColors.dominantColors( uiImage: uiImage, quality: .fair, algorithm: .CIE94, maxCount: 5, options: [], sorting: .lightness, deltaColors: 15 ) ``` -------------------------------- ### Extract Dominant Colors from NSImage Source: https://context7.com/dendmitriev/dominantcolors/llms.txt Convenience methods for macOS to extract colors directly from NSImage instances. ```swift import AppKit import DominantColors let nsImage = NSImage(named: "landscape")! // Quick extraction let colors = try DominantColors.dominantColors(nsImage: nsImage, maxCount: 6) // Returns: [NSColor] - Array of NSColor instances // With full options let macColors = try DominantColors.dominantColors( nsImage: nsImage, quality: .high, algorithm: .CIE94, maxCount: 8, options: [.excludeGray], sorting: .frequency ) ``` -------------------------------- ### Extract Dominant Colors from CGImage Source: https://context7.com/dendmitriev/dominantcolors/llms.txt Primary method for extracting dominant colors from a CGImage. It groups similar colors and returns a palette of the most prominent ones. ```APIDOC ## Extract Dominant Colors from CGImage ### Description Extracts dominant colors from a CGImage by grouping similar colors using configurable color difference algorithms. ### Method `DominantColors.dominantColors(image:quality:algorithm:maxCount:options:sorting:deltaColors:resultLog:timeLog:)` ### Endpoint N/A (Swift Library Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import DominantColors let cgImage: CGImage = // ... load your image let dominantColors = try DominantColors.dominantColors(image: cgImage, maxCount: 6) ``` ### Response #### Success Response (200) - **[CGColor]** - Array of dominant colors sorted by frequency. #### Response Example ```json [ "red", "orange", "yellow", "green", "blue", "purple" ] ``` ### Advanced Usage Example ```swift let colors = try DominantColors.dominantColors( image: cgImage, quality: .high, // .low, .fair, .high, or .best algorithm: .CIEDE2000, // .euclidean, .CIE76, .CIE94, .CIEDE2000, or .CMC maxCount: 8, // Maximum colors to return options: [.excludeBlack, .excludeWhite, .excludeGray], // Filter options sorting: .darkness, // .frequency, .darkness, or .lightness deltaColors: 10, // Similarity threshold (lower = more shades) resultLog: true, // Print results to console timeLog: true // Print timing info ) // Output: DominantColor extract colors: [red, orange, yellow, green, blue, purple], count: 6, time: 0.045s ``` ``` -------------------------------- ### Extract Dominant Colors from NSImage (macOS) Source: https://context7.com/dendmitriev/dominantcolors/llms.txt Convenience method for macOS applications that works directly with NSImage and returns NSColor instances. ```APIDOC ## Extract Dominant Colors from NSImage (macOS) ### Description Convenience method for macOS applications that works directly with `NSImage` and returns `NSColor` instances. ### Method `DominantColors.dominantColors(nsImage:quality:algorithm:maxCount:options:sorting:deltaColors:)` ### Endpoint N/A (Swift Library Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import AppKit import DominantColors let nsImage = NSImage(named: "landscape")! // Quick extraction let colors = try DominantColors.dominantColors(nsImage: nsImage, maxCount: 6) ``` ### Response #### Success Response (200) - **[NSColor]** - Array of `NSColor` instances. #### Response Example ```json [ "#0000FF", "#FF00FF", "#00FFFF" ] ``` ### Full Options Example ```swift let macColors = try DominantColors.dominantColors( nsImage: nsImage, quality: .high, algorithm: .CIE94, maxCount: 8, options: [.excludeGray], sorting: .frequency ) ``` ``` -------------------------------- ### Compute Complementary Color Source: https://context7.com/dendmitriev/dominantcolors/llms.txt Computes the complementary color on the color wheel by inverting RGB values. Useful for creating contrasting accents. ```swift import CoreGraphics import DominantColors let blue = CGColor(red: 0, green: 0, blue: 1, alpha: 1) let complementary = blue.complementaryColor // Returns: CGColor - Yellow (1, 1, 0, 1) let red = CGColor(red: 1, green: 0, blue: 0, alpha: 1) let cyan = red.complementaryColor // Returns: CGColor - Cyan (0, 1, 1, 1) // Use for creating contrasting accents let dominantColor = CGColor(red: 0.2, green: 0.5, blue: 0.8, alpha: 1) // Blue let accentColor = dominantColor.complementaryColor // Orange-ish ``` -------------------------------- ### Interpolate Colors in a Gradient Source: https://context7.com/dendmitriev/dominantcolors/llms.txt Interpolates colors along a gradient defined by an array of CGColors. Useful for creating smooth color transitions or sampling colors at specific points. ```swift import CoreGraphics import DominantColors // Define a gradient with multiple colors let gradientColors: [CGColor] = [ CGColor(red: 1, green: 0, blue: 0, alpha: 1), // Red CGColor(red: 1, green: 1, blue: 0, alpha: 1), // Yellow CGColor(red: 0, green: 1, blue: 0, alpha: 1), // Green CGColor(red: 0, green: 0, blue: 1, alpha: 1) // Blue ] // Get color at percentage (0-100) let colorAt25Percent = gradientColors.gradientColor(percent: 25) // Returns: CGColor - Orange (between red and yellow) let colorAt50Percent = gradientColors.gradientColor(percent: 50) // Returns: CGColor - Yellow-green let colorAt75Percent = gradientColors.gradientColor(percent: 75) // Returns: CGColor - Cyan-ish (between green and blue) // Get color at specific point in a size range let colorAtPoint = gradientColors.gradientColor(at: 3, size: 10) // Returns: CGColor at position 3 of 10 // Generate array of interpolated colors let expandedGradient = gradientColors.gradientColors(in: 20) // Returns: [CGColor] - 20 colors smoothly interpolated across the gradient ``` -------------------------------- ### Extract Dominant Colors from UIImage (iOS) Source: https://context7.com/dendmitriev/dominantcolors/llms.txt Convenience method for iOS applications that works directly with UIImage and returns UIColor instances. ```APIDOC ## Extract Dominant Colors from UIImage (iOS) ### Description Convenience method for iOS applications that works directly with `UIImage` and returns `UIColor` instances. ### Method `DominantColors.dominantColors(uiImage:quality:algorithm:maxCount:options:sorting:deltaColors:)` or `uiImage.dominantColors(max:options:)` extension. ### Endpoint N/A (Swift Library Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import UIKit import DominantColors let uiImage = UIImage(named: "photo")! // Quick extraction with defaults let colors = try DominantColors.dominantColors(uiImage: uiImage, maxCount: 6) // Using the UIImage extension let dominantColors = try uiImage.dominantColors(max: 6, options: [.excludeWhite]) ``` ### Response #### Success Response (200) - **[UIColor]** - Array of `UIColor` instances. #### Response Example ```json [ "#FF0000", "#FFA500", "#FFFF00" ] ``` ### Full Customization Example ```swift let customColors = try DominantColors.dominantColors( uiImage: uiImage, quality: .fair, algorithm: .CIE94, maxCount: 5, options: [], sorting: .lightness, deltaColors: 15 ) ``` ``` -------------------------------- ### Calculate Average Colors by Image Segments in Swift Source: https://context7.com/dendmitriev/dominantcolors/llms.txt Divides images into horizontal segments to extract average colors, supporting platform-specific types like UIImage and NSImage with various sorting options. ```swift import DominantColors let cgImage: CGImage = // ... your image // Get average colors across 8 horizontal segments let averageColors = try DominantColors.averageColors( image: cgImage, count: 8, sorting: .frequency ) // Returns: [CGColor] - One color per segment, left to right // iOS example - create a color strip let uiImage = UIImage(named: "sunset")! let stripColors = try DominantColors.averageColors( uiImage: uiImage, count: 12, sorting: .frequency // Maintains left-to-right order ) // Returns: [UIColor] - 12 colors representing horizontal bands // macOS example with lightness sorting let nsImage = NSImage(named: "gradient")! let sortedAverages = try DominantColors.averageColors( nsImage: nsImage, count: 6, sorting: .lightness ) // Returns: [NSColor] - Sorted from lightest to darkest ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.