-
-
Save gopalkrishnareddy/b01a1579204abacd32e5f752e6709290 to your computer and use it in GitHub Desktop.
Foreground text color based on background color #SwiftUI
This file contains 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
// Taken from Apple's App Dev Training: https://developer.apple.com/tutorials/app-dev-training/ | |
/// This color is either black or white, whichever is more accessible when viewed against the scrum color. | |
var accessibleFontColor: Color { | |
var red: CGFloat = 0 | |
var green: CGFloat = 0 | |
var blue: CGFloat = 0 | |
UIColor(self).getRed(&red, green: &green, blue: &blue, alpha: nil) | |
return isLightColor(red: red, green: green, blue: blue) ? .black : .white | |
} | |
private func isLightColor(red: CGFloat, green: CGFloat, blue: CGFloat) -> Bool { | |
let lightRed = red > 0.65 | |
let lightGreen = green > 0.65 | |
let lightBlue = blue > 0.65 | |
let lightness = [lightRed, lightGreen, lightBlue].reduce(0) { $1 ? $0 + 1 : $0 } | |
return lightness >= 2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment