Skip to content

Instantly share code, notes, and snippets.

@JTostitos
Last active July 29, 2024 20:42
Show Gist options
  • Save JTostitos/b4f00a157aee00407a7651f4b56dd295 to your computer and use it in GitHub Desktop.
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.
#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)
}
}
@JTostitos
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment