Swift Extension to Add Two Colours Together

The following extension makes it really simple to blend two colours together into a non-transparent colour.

For example, if you have a red colour (UIColor.redColor()) and want to make it slightly darker, you could add UIColor(white: 0, alpha: 0.1) to it (10% black).

This is achieved using the following code, which extracts the red, green, blue and alpha channels, and adds them together, returning a new UIColor object.

import UIKit

extension UIColor {

    func add(overlay: UIColor) -> UIColor {
        var bgR: CGFloat = 0
        var bgG: CGFloat = 0
        var bgB: CGFloat = 0
        var bgA: CGFloat = 0

        var fgR: CGFloat = 0
        var fgG: CGFloat = 0
        var fgB: CGFloat = 0
        var fgA: CGFloat = 0

        self.getRed(&bgR, green: &bgG, blue: &bgB, alpha: &bgA)
        overlay.getRed(&fgR, green: &fgG, blue: &fgB, alpha: &fgA)

        let r = fgA * fgR + (1 - fgA) * bgR
        let g = fgA * fgG + (1 - fgA) * bgG
        let b = fgA * fgB + (1 - fgA) * bgB

        return UIColor(red: r, green: g, blue: b, alpha: 1.0)
    }
}

You can now make red slightly darker using the following:

let red = UIColor.redColor()  
let black10 = UIColor(white: 0, alpha: 0.1)

let darkerRed = red.add(black10)  

And of course, in Swift you can make this even easier by overriding the + operator.

func +(lhs: UIColor, rhs: UIColor) -> UIColor {  
    return lhs.add(rhs)
}

This means you can now use:

let darkerRed = red + black10