Skip to content

Instantly share code, notes, and snippets.

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 gopalkrishnareddy/b01a1579204abacd32e5f752e6709290 to your computer and use it in GitHub Desktop.
Save gopalkrishnareddy/b01a1579204abacd32e5f752e6709290 to your computer and use it in GitHub Desktop.
Foreground text color based on background color #SwiftUI
// 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