Last active
July 29, 2024 20:42
-
-
Save JTostitos/b4f00a157aee00407a7651f4b56dd295 to your computer and use it in GitHub Desktop.
Check if Color is Light or Dark. Returns a bool so that you can determine what color to make the text shown in front of the light 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
#if os(macOS) | |
typealias PlatformColor = NSColor | |
#else | |
typealias PlatformColor = UIColor | |
#endif | |
/// This was primarilly used in a SwiftUI app which is why you see the extension is on Color but theoretically, the code inside the function below could be used in just UIKit as the underlying code has nothing to do with SwiftUI. | |
extension Color { | |
func isLightColor() -> Bool? { | |
let platformColor = PlatformColor(self).cgColor | |
let uic = platformColor.converted(to: CGColorSpaceCreateDeviceRGB(), intent: .defaultIntent, options: nil) | |
guard let components = uic?.components, components.count >= 3 else { | |
return nil | |
} | |
let brightness = Float(((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000) | |
return (brightness > 0.7) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was primarily used in a SwiftUI app which is why you see the extension is on Color but theoretically, the code inside the function below could be used in just UIKit as the underlying code has nothing to do with SwiftUI.