在Swift中获取UIImage的平均颜色 [英] Get average color of UIImage in Swift

查看:152
本文介绍了在Swift中获取UIImage的平均颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近正尝试从此处进入Swift.但是,无论图像如何,我都会一直保持白色.这是我的代码:

I was recently attempting to convert the code from here into Swift. However, I keep getting a white color, no matter the image. Here's my code:

// Playground - noun: a place where people can play

import UIKit

extension UIImage {
    func averageColor() -> UIColor {
        var colorSpace = CGColorSpaceCreateDeviceRGB()
        var rgba: [CGFloat] = [0,0,0,0]
        var context = CGBitmapContextCreate(&rgba, 1, 1, 8, 4, colorSpace, CGBitmapInfo.fromRaw(CGImageAlphaInfo.PremultipliedLast.toRaw())!)
        rgba

        CGContextDrawImage(context, CGRectMake(0, 0, 1, 1), self.CGImage)

        if rgba[3] > 0 {
            var alpha = rgba[3] / 255
            var multiplier = alpha / 255
            return UIColor(red: rgba[0] * multiplier, green: rgba[1] * multiplier, blue: rgba[2] * multiplier, alpha: alpha)
        } else {
            return UIColor(red: rgba[0] / 255, green: rgba[1] / 255, blue: rgba[2] / 255, alpha: rgba[3] / 255)
        }
    }
}

var img = UIImage(data: NSData(contentsOfURL: NSURL(string: "http://upload.wikimedia.org/wikipedia/commons/c/c3/Aurora_as_seen_by_IMAGE.PNG")))

img.averageColor()

谢谢.

推荐答案

iOS 9中的CoreImage:使用CIAreaAverage过滤器并传递要平均的整个图像的范围.

CoreImage in iOS 9: use the CIAreaAverage filter and pass the extent of your entire image to be averaged.

此外,由于它既可以在GPU上运行,也可以作为高度优化的CPU CIKernel运行,因此速度要快得多.

Plus, it's much faster since it'll either be running on the GPU or as a highly-optimized CPU CIKernel.

这篇关于在Swift中获取UIImage的平均颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆