This repository was archived by the owner on Oct 30, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathUIImage+Extensions.swift
46 lines (39 loc) · 2 KB
/
UIImage+Extensions.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//
// UIImage+Extensions.swift
// Slide Widgets
//
// Created by Jonathan Cole on 9/15/20.
// Copyright © 2020 Haptic Apps. All rights reserved.
//
import UIKit
extension UIImage {
/// Average color of the image, nil if it cannot be found
var averageColor: UIColor? {
// convert our image to a Core Image Image
guard let inputImage = CIImage(image: self) else { return nil }
// Create an extent vector (a frame with width and height of our current input image)
let extentVector = CIVector(x: inputImage.extent.origin.x,
y: inputImage.extent.origin.y,
z: inputImage.extent.size.width,
w: inputImage.extent.size.height)
// create a CIAreaAverage filter, this will allow us to pull the average color from the image later on
guard let filter = CIFilter(name: "CIAreaAverage",
parameters: [kCIInputImageKey: inputImage, kCIInputExtentKey: extentVector]) else { return nil }
guard let outputImage = filter.outputImage else { return nil }
// A bitmap consisting of (r, g, b, a) value
var bitmap = [UInt8](repeating: 0, count: 4)
let context = CIContext(options: [.workingColorSpace: kCFNull!])
// Render our output image into a 1 by 1 image supplying it our bitmap to update the values of (i.e the rgba of the 1 by 1 image will fill out bitmap array
context.render(outputImage,
toBitmap: &bitmap,
rowBytes: 4,
bounds: CGRect(x: 0, y: 0, width: 1, height: 1),
format: .RGBA8,
colorSpace: nil)
// Convert our bitmap images of r, g, b, a to a UIColor
return UIColor(red: CGFloat(bitmap[0]) / 255,
green: CGFloat(bitmap[1]) / 255,
blue: CGFloat(bitmap[2]) / 255,
alpha: CGFloat(bitmap[3]) / 255)
}
}