Last active
December 4, 2024 21:40
-
-
Save drewolbrich/89b4fcbf38620f29bce02c99f7e49221 to your computer and use it in GitHub Desktop.
Blends together two UIColors, returning a dynamic color
This file contains hidden or 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 | |
extension UIColor { | |
/// Creates a dynamic color from the receiver blended with another color. | |
/// | |
/// If `weight` is 0, the color of `self` is returned. If `weight` is 1, the color | |
/// of `otherColor` is returned. | |
/// | |
/// This method works correctly with light and dark mode. A dynamic color is | |
/// returned, so if the user switches to dark mode, the dark mode versions of `self` | |
/// and `otherColor` will be blended together and displayed. | |
func blended(with otherColor: UIColor, weight: CGFloat) -> UIColor { | |
func blend(_ baseColor: UIColor, with otherColor: UIColor, weight: CGFloat) -> UIColor { | |
var red: CGFloat = 0 | |
var green: CGFloat = 0 | |
var blue: CGFloat = 0 | |
var alpha: CGFloat = 0 | |
baseColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha) | |
var otherRed: CGFloat = 0 | |
var otherGreen: CGFloat = 0 | |
var otherBlue: CGFloat = 0 | |
var otherAlpha: CGFloat = 0 | |
otherColor.getRed(&otherRed, green: &otherGreen, blue: &otherBlue, alpha: &otherAlpha) | |
func mix(_ x: CGFloat, _ y: CGFloat, _ a: CGFloat) -> CGFloat { | |
return (1 - a)*x + a*y | |
} | |
return UIColor( | |
red: mix(red, otherRed, weight), | |
green: mix(green, otherGreen, weight), | |
blue: mix(blue, otherBlue, weight), | |
alpha: mix(alpha, otherAlpha, weight) | |
) | |
} | |
return UIColor(dynamicProvider: { traitCollection in | |
var result: UIColor = .white | |
traitCollection.performAsCurrent { | |
result = blend(self, with: otherColor, weight: weight) | |
} | |
return result | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment