Skip to content

Instantly share code, notes, and snippets.

@delputnam
Created June 25, 2016 12:27
Show Gist options
  • Save delputnam/2d80e7b4bd9363fd221d131e4cfdbd8f to your computer and use it in GitHub Desktop.
Save delputnam/2d80e7b4bd9363fd221d131e4cfdbd8f to your computer and use it in GitHub Desktop.
Determine if a UIColor is light or dark
// Returns black if the given background color is light or white if the given color is dark
func textColor(bgColor: UIColor) -> UIColor {
var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 0.0
var brightness: CGFloat = 0.0
bgColor.getRed(&r, green: &g, blue: &b, alpha: &a)
// algorithm from: http://www.w3.org/WAI/ER/WD-AERT/#color-contrast
brightness = ((r * 299) + (g * 587) + (b * 114)) / 1000;
if (brightness < 0.5) {
return UIColor.white()
}
else {
return UIColor.black()
}
}
// returns true if color is light, false if it is dark
extension UIColor
{
func isLight() -> Bool
{
// algorithm from: http://www.w3.org/WAI/ER/WD-AERT/#color-contrast
let components = CGColorGetComponents(self.CGColor)
let brightness = ((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000
if brightness < 0.5
{
return false
}
else
{
return true
}
}
}
@alexeyhatkevich
Copy link

isn't working, alpha was skipped

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