Created
June 25, 2016 12:27
-
-
Save delputnam/2d80e7b4bd9363fd221d131e4cfdbd8f to your computer and use it in GitHub Desktop.
Determine if a UIColor is light or dark
This file contains hidden or 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
// 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() | |
} | |
} |
This file contains hidden or 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
// 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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
isn't working, alpha was skipped