Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
folium-app
GitHub Repository: folium-app/Folium
Path: blob/a-new-beginning/Folium-iOS/Extensions/UIImage.swift
2 views
//
//  UIImage.swift
//  Folium-iOS
//
//  Created by Jarrod Norwell on 20/7/2025.
//

import CoreImage
import UIKit

extension UIImage {
    var dominantColour: UIColor? {
        let size = CGSize(width: 10, height: 10)
        
        UIGraphicsBeginImageContext(size)
        defer {
            UIGraphicsEndImageContext()
        }
        
        draw(in: CGRect(origin: .zero, size: size))
        guard let contextImage = UIGraphicsGetImageFromCurrentImageContext(),
              let cgImage = contextImage.cgImage,
              let data = cgImage.dataProvider?.data,
              let pixelPtr = CFDataGetBytePtr(data) else {
            return nil
        }
        
        var colorCounts: [UInt32: Int] = [:]
        let width = cgImage.width
        let height = cgImage.height
        let bytesPerPixel = 4
        
        for y in 0..<height {
            for x in 0..<width {
                let offset = (y * width + x) * bytesPerPixel
                let r = pixelPtr[offset]
                let g = pixelPtr[offset + 1]
                let b = pixelPtr[offset + 2]
                let a = pixelPtr[offset + 3]
                
                guard a > 0 else { continue } // Ignore fully transparent pixels
                
                let colorKey = UInt32(r) << 24 | UInt32(g) << 16 | UInt32(b) << 8 | UInt32(a)
                colorCounts[colorKey, default: 0] += 1
            }
        }
        
        guard let (mostFrequentColor, _) = colorCounts.max(by: { $0.value < $1.value }) else {
            return nil
        }
        
        let r = CGFloat((mostFrequentColor >> 24) & 0xFF) / 255.0
        let g = CGFloat((mostFrequentColor >> 16) & 0xFF) / 255.0
        let b = CGFloat((mostFrequentColor >> 8) & 0xFF) / 255.0
        let a = CGFloat(mostFrequentColor & 0xFF) / 255.0
        
        return UIColor(red: r, green: g, blue: b, alpha: a)
    }
    
    func hierarched(_ colour: UIColor = .white) -> UIImage? {
        self.applyingSymbolConfiguration(.init(hierarchicalColor: colour))
    }
}