Check if UIColor is dark or bright?

前端 未结 14 2027
醉酒成梦
醉酒成梦 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:38

    For me using only CGColorGetComponents didn't worked, I get 2 components for UIColors like white. So I have to check the color spaceModel first. This is what I came up with that ended up being the swift version of @mattsven's answer.

    Color space taken from here: https://stackoverflow.com/a/16981916/4905076

    extension UIColor {
        func isLight() -> Bool {
            if let colorSpace = self.cgColor.colorSpace {
                if colorSpace.model == .rgb {
                    guard let components = cgColor.components, components.count > 2 else {return false}
    
                    let brightness = ((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000
    
                    return (brightness > 0.5)
                }
                else {
                    var white : CGFloat = 0.0
    
                    self.getWhite(&white, alpha: nil)
    
                    return white >= 0.5
                }
            }
    
            return false
        }
    

提交回复
热议问题