//
//  UIImageView.swift
//  relax.offline.mp3.music
//
//  Created by Mr.Zhou on 2024/7/23.
//

import UIKit
extension UIImage {
    
    /// 获取图片大致颜色
    /// - Parameter rect: 截取的范围
    /// - Returns: 返回的颜色值
    func dominantColor(in rect: CGRect) -> UIColor? {
        guard let cgImage = self.cgImage?.cropping(to: rect) else { return nil }
        
        let context = CGContext(
            data: nil,
            width: 1,
            height: 1,
            bitsPerComponent: cgImage.bitsPerComponent,
            bytesPerRow: cgImage.bytesPerRow,
            space: cgImage.colorSpace ?? CGColorSpaceCreateDeviceRGB(),
            bitmapInfo: cgImage.bitmapInfo.rawValue
        )
        
        context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: 1, height: 1))
        
        guard let pixelData = context?.data else { return nil }
        
        let data = pixelData.bindMemory(to: UInt8.self, capacity: 4)
        let r = CGFloat(data[0]) / 255.0
        let g = CGFloat(data[1]) / 255.0
        let b = CGFloat(data[2]) / 255.0
        let a = CGFloat(data[3]) / 255.0
        
        return UIColor(red: r, green: g, blue: b, alpha: a)
    }
    
    func topAndBottomDominantColors() -> (topColor: UIColor?, bottomColor: UIColor?) {
        guard let cgImage = self.cgImage else { return (nil, nil) }
        
        let height = self.size.height
        let topRect = CGRect(x: 0, y: 0, width: self.size.width, height: height / 2)
        let bottomRect = CGRect(x: 0, y: height / 2, width: self.size.width, height: height / 2)
        
        let topColor = self.dominantColor(in: topRect)
        let bottomColor = self.dominantColor(in: bottomRect)
        
        return (topColor, bottomColor)
    }
}
