Skip to content

Instantly share code, notes, and snippets.

@yannxou
Created December 23, 2020 09:55
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save yannxou/689edc3c9e443f13a832ea1afcfaa88a to your computer and use it in GitHub Desktop.
Save yannxou/689edc3c9e443f13a832ea1afcfaa88a 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