Can I mix two UIColor together?

后端 未结 6 1511
暖寄归人
暖寄归人 2021-01-12 05:51

I have colorA which is [UIColor blueColor], and colorB, which is [UIColor redColor]. Is this possible for me to render a [UIColor purple]

6条回答
  •  被撕碎了的回忆
    2021-01-12 06:43

    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)
    

提交回复
热议问题