Check if UIColor is dark or bright?

前端 未结 14 2032
醉酒成梦
醉酒成梦 2020-11-29 17:20

I need to determine whether a selected UIColor (picked by the user) is dark or bright, so I can change the color of a line of text that sits on top of that color, for better

14条回答
  •  爱一瞬间的悲伤
    2020-11-29 17:27

    Following method is find color is light or dark in Swift language based on white in color.

    func isLightColor(color: UIColor) -> Bool 
    {
       var white: CGFloat = 0.0
       color.getWhite(&white, alpha: nil)
    
       var isLight = false
    
       if white >= 0.5
       {
           isLight = true
           NSLog("color is light: %f", white)
       }
       else
       {
          NSLog("Color is dark: %f", white)
       }
    
       return isLight
    }
    

    Following method is find color is light or dark in Swift using color components.

    func isLightColor(color: UIColor) -> Bool 
    {
         var isLight = false
    
         var componentColors = CGColorGetComponents(color.CGColor)
    
         var colorBrightness: CGFloat = ((componentColors[0] * 299) + (componentColors[1] * 587) + (componentColors[2] * 114)) / 1000;
         if (colorBrightness >= 0.5)
         {
            isLight = true
            NSLog("my color is light")
         }
         else
         {
            NSLog("my color is dark")
         }  
         return isLight
    }
    

提交回复
热议问题