Created
January 19, 2023 11:32
-
-
Save ilia3546/a90fcdc208b49f69be95ecd854544d73 to your computer and use it in GitHub Desktop.
Blending two UIColor's. Swift implementation of JordanDelcros's JS algorithm https://gist.github.com/JordanDelcros/518396da1c13f75ee057
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
public extension UIColor { | |
/** | |
Blend current color with some overlay | |
Source - [JordanDelcros's JS algorithm](https://gist.github.com/JordanDelcros/518396da1c13f75ee057) | |
*/ | |
func blended(with overlay: UIColor) -> UIColor { | |
let base = self.components | |
let overlay = overlay.components | |
let resultAlpha = 1 - (1 - overlay.alpha) * (1 - base.alpha) | |
let blendComponents = { (baseComponent: CGFloat, overlayComponent: CGFloat) -> CGFloat in | |
(baseComponent * base.alpha * (1 - overlay.alpha) / resultAlpha) + (overlayComponent * overlay.alpha / resultAlpha) | |
} | |
return UIColor( | |
red: blendComponents(base.red, overlay.red), | |
green: blendComponents(base.green, overlay.green), | |
blue: blendComponents(base.blue, overlay.blue), | |
alpha: resultAlpha | |
) | |
} | |
var components: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { | |
var red: CGFloat = 0 | |
var green: CGFloat = 0 | |
var blue: CGFloat = 0 | |
var alpha: CGFloat = 0 | |
getRed(&red, green: &green, blue: &blue, alpha: &alpha) | |
return (red, green, blue, alpha) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment