获取UIImage的平均颜色

时间:2018-08-03 16:24:25

标签: ios swift uiimage

我正在尝试做类似于Twitter和许多其他应用程序的操作-将背景设置为图像的平均颜色。问题是,根据我拥有的图像阵列,它将获得最后的平均颜色,并且永远不会更改。这些图像所在的UIScrollView的背景色。我不知道为什么。

这是我用来提取平均颜色的代码(PS:我发现它是here

import UIKit

extension UIImage {
    var averageColor: UIColor? {
        guard let inputImage = CIImage(image: self) else { return nil }
        let extentVector = CIVector(x: inputImage.extent.origin.x, y: inputImage.extent.origin.y, z: inputImage.extent.size.width, w: inputImage.extent.size.height)

        guard let filter = CIFilter(name: "CIAreaAverage", withInputParameters: [kCIInputImageKey: inputImage, kCIInputExtentKey: extentVector]) else { return nil }
        guard let outputImage = filter.outputImage else { return nil }

        var bitmap = [UInt8](repeating: 0, count: 4)
        let context = CIContext(options: [kCIContextWorkingColorSpace: kCFNull])
        context.render(outputImage, toBitmap: &bitmap, rowBytes: 4, bounds: CGRect(x: 0, y: 0, width: 1, height: 1), format: kCIFormatRGBA8, colorSpace: nil)

        return UIColor(red: CGFloat(bitmap[0]) / 255, green: CGFloat(bitmap[1]) / 255, blue: CGFloat(bitmap[2]) / 255, alpha: CGFloat(bitmap[3]) / 255)
    }
}

这是viewDidLoad()中被调用的函数的代码:

    func setScrollView() {
    for  i in stride(from: 0, to: imagelist.count, by: 1) {
        var frame = CGRect.zero
        frame.origin.x = self.scrollView.frame.size.width * CGFloat(i)
        frame.origin.y = 0
        frame.size = self.scrollView.frame.size
        scrollView.isPagingEnabled = true

        let newUIImageView = UIImageView()
        let myImage:UIImage = UIImage(named: imagelist[i])!
        let bgColorFromImage = myImage.averageColor
        newUIImageView.image = myImage
        newUIImageView.frame =  frame

        newUIImageView.contentMode = UIViewContentMode.scaleAspectFit

        scrollView.backgroundColor = bgColorFromImage // Changes the color to the average color of the image
        scrollView.addSubview(newUIImageView)

        self.scrollView.contentSize = CGSize(width: self.scrollView.frame.size.width * CGFloat(imagelist.count), height: self.scrollView.frame.size.height)
        pageControl.addTarget(self, action: #selector(changePage), for: UIControlEvents.valueChanged)
    }
}

1 个答案:

答案 0 :(得分:1)

我知道了。我需要创建一个UIColor数组来存储图像的所有颜色:

var colors = [UIColor]()

然后在setScrollView()中添加颜色,如下所示:

colors.append(myImage.averageColor!)

最后,在scrollViewDidEndDecelerating(_ scrollView: UIScrollView)中像这样设置背景:

scrollView.backgroundColor = colors[Int(pageNumber)]