Last active
August 12, 2021 05:42
-
-
Save froggomad/cc4fa0f8e77bf548d23606bcd8290fce to your computer and use it in GitHub Desktop.
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 { | |
// credit: @beyowulf | |
// https://stackoverflow.com/questions/47365583/determining-text-color-from-the-background-color-in-swift/47366748 | |
var isDarkColor: Bool { | |
var r, g, b, a: CGFloat | |
(r, g, b, a) = (0, 0, 0, 0) | |
self.getRed(&r, green: &g, blue: &b, alpha: &a) | |
let lum = 0.2126 * r + 0.7152 * g + 0.0722 * b | |
return lum < 0.50 | |
} | |
static func contextualColor(for colorToCompareAgainst: UIColor, | |
lightColorToUse: UIColor = .white, | |
darkColorToUse: UIColor = .black) -> UIColor { | |
colorToCompareAgainst.isDarkColor ? lightColorToUse : darkColorToUse | |
} | |
} | |
extension UIView { | |
func setContextualBackgroundColor(for color: UIColor) { | |
backgroundColor = .contextualColor(for: color) | |
} | |
} | |
extension UILabel { | |
func setContextualTextColor(for color: UIColor) { | |
textColor = .contextualColor(for: color) | |
} | |
} | |
extension UIButton { | |
func setContextualLinkColor(for color: UIColor) { | |
let contextualColor: UIColor = .contextualColor(for: color, | |
lightColorToUse: .link, | |
darkColorToUse: .white) | |
setTitleColor(contextualColor, for: .normal) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment