El Tomato El Tomato - 6 months ago 22
Swift Question

Creating an Array of CGColors from an Array of UIColors or NSColors

I've been testing

CAGradientLayer
to create gradient colors for iOS and Mac OS X (Cocoa). For example, I have the following lines of code to create gradient colors for iOS.

let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = [UIColor.orangeColor().CGColor,UIColor.redColor().CGColor]
gradient.locations = [0.1,0.9]
self.view.layer.insertSublayer(gradient,atIndex:0)


Now, what I have is an array of colors (
UIColor
or
NSColor
), depending on the development platform. If I create an array containing
UIColor
(or
NSColor
) objects programmatically, starting with

var cArray = [UIColor]()


or

var cArray = [NSColor]()


, how can I create an array containing CGColors with them? I'm thinking that this topic might be related. One problem is that I don't know how to declare and initialize an array of CGColor objects.

Thank you

Answer

You could do:

extension _ArrayType where Generator.Element == UIColor {
    func CGColors() -> [CGColorRef] {
        var cgColorArray: [CGColorRef] = []

        for color in self {
            cgColorArray.append(color.CGColor)
        }

        return cgColorArray
    }
}

Use it like so:

let colors: [UIColor] = [UIColor.redColor(), UIColor.orangeColor()]
colors.CGColors()

Repeat for NSColor.