I have colorA which is [UIColor blueColor]
, and colorB, which is [UIColor redColor]
. Is this possible for me to render a [UIColor purple]
Swift5 UIColor Extension
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)
}
static func +(lhs: UIColor, rhs: UIColor) -> UIColor {
return lhs.add(rhs)
}
}
Usage
let opacity: CGFloat = 0.6
let start = UIColor.red
let end = UIColor.blue
let combined = start.withAlphaComponent(opacity) + end.withAlphaComponent(1-opacity)