Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@drewolbrich
Created December 12, 2021 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drewolbrich/7738bd61f720a6c045f05af421869bc7 to your computer and use it in GitHub Desktop.
Save drewolbrich/7738bd61f720a6c045f05af421869bc7 to your computer and use it in GitHub Desktop.
Attenuates a UIColor, returning a dynamic color
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