Check if UIColor is dark or bright?

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

    Swift 4 Version

    extension UIColor {
        func isLight() -> Bool {
            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)
        }
    }
    

提交回复
热议问题