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 | |
| } | |
| } | |
| } | 
I need to warn you about this function. For white or black, the color contains only 2 components so the code above would crash...
The textColor implementation seems better :
public extension UIColor {
    func isLight() -> Bool {
        // algorithm from: http://www.w3.org/WAI/ER/WD-AERT/#color-contrast
        var r: CGFloat = 0.0
        var g: CGFloat = 0.0
        var b: CGFloat = 0.0
        var a: CGFloat = 0.0
        
        getRed(&r, green: &g, blue: &b, alpha: &a)
        
        let brightness = ((r * 299) + (g * 587) + (b * 114)) / 1_000
        return brightness >= 0.5
    }
}isn't working, alpha was skipped
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Swift 5 code
`
extension UIColor{
func isLight() -> Bool{
// algorithm from: http://www.w3.org/WAI/ER/WD-AERT/#color-contrast
if let components = self.cgColor.components{
let firstComponent = (components[0] * 299)
let secondComponent = (components[1] * 587)
let ThirdComponent = (components[2] * 114)
}`