Music_Player3/relax.offline.mp3.music/MP/Common/Extension(扩展)/UIImageView.swift
2024-07-25 19:44:30 +08:00

53 lines
1.7 KiB
Swift

//
// 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)
}
}