Skip to content

Instantly share code, notes, and snippets.

@juliensagot
Last active December 9, 2019 08:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juliensagot/602f27776fdf0e0d7c92dd52a2f94662 to your computer and use it in GitHub Desktop.
Save juliensagot/602f27776fdf0e0d7c92dd52a2f94662 to your computer and use it in GitHub Desktop.
Get the average color of a UIImage. (Swift 4.2, Xcode 10.0)
import UIKit
extension UIImage {
var averageColor: UIColor? {
guard let inputImage = self.ciImage ?? CIImage(image: self) else { return nil }
guard let filter = CIFilter(name: "CIAreaAverage", parameters: [kCIInputImageKey: inputImage, kCIInputExtentKey: CIVector(extent: inputImage.extent)])
else { return nil }
guard let outputImage = filter.outputImage else { return nil }
var bitmap = [UInt8](repeating: 0, count: 4)
let context = CIContext(options: [CIContextOption.workingColorSpace : kCFNull])
let outputImageRect = CGRect(x: 0, y: 0, width: 1, height: 1)
context.render(outputImage, toBitmap: &bitmap, rowBytes: 4, bounds: outputImageRect, format: CIFormat.RGBA8, colorSpace: nil)
return UIColor(red: CGFloat(bitmap[0]) / 255, green: CGFloat(bitmap[1]) / 255, blue: CGFloat(bitmap[2]) / 255, alpha: CGFloat(bitmap[3) / 255)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment