Created
December 12, 2021 18:48
-
-
Save drewolbrich/7738bd61f720a6c045f05af421869bc7 to your computer and use it in GitHub Desktop.
Attenuates a UIColor, 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 with attenuated brightness. | |
/// | |
/// This method works correctly with light and dark mode. A dynamic color is | |
/// returned, so if the user switches to dark mode, the attenuated dark mode version of `self` | |
/// will be displayed. | |
func attenuated(by attenuation: CGFloat) -> UIColor { | |
func attenuate(_ baseColor: UIColor, by attenuation: CGFloat) -> UIColor { | |
var hue: CGFloat = 0 | |
var saturation: CGFloat = 0 | |
var brightness: CGFloat = 0 | |
var alpha: CGFloat = 0 | |
baseColor.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) | |
brightness *= attenuation | |
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha) | |
} | |
return UIColor(dynamicProvider: { traitCollection in | |
var result: UIColor = .white | |
traitCollection.performAsCurrent { | |
result = attenuate(self, by: attenuation) | |
} | |
return result | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment