0

Upon reading a SO thread about checking whether a color is bright, I found this piece of code by @josh-fuggle:

extension UIColor {

    // Check if the color is light or dark, as defined by the injected lightness threshold.
    // Some people report that 0.7 is best. I suggest to find out for yourself.
    // A nil value is returned if the lightness couldn't be determined.
    func isLight(threshold: Float = 0.5) -> Bool? {
        let originalCGColor = self.cgColor

        // Now we need to convert it to the RGB colorspace. UIColor.white / UIColor.black are greyscale and not RGB.
        // If you don't do this then you will crash when accessing components index 2 below when evaluating greyscale colors.
        let RGBCGColor = originalCGColor.converted(to: CGColorSpaceCreateDeviceRGB(), intent: .defaultIntent, options: nil)
        guard let components = RGBCGColor?.components else {
            return nil
        }
        guard components.count >= 3 else {
            return nil
        }

        let brightness = Float(((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000)
        return (brightness > threshold)
    }
}

In the code, the guard statements ensure that the converted color is not nil, and has three or more components.

So my question is, is there any color that makes the whole isLight function return nil?

sohnryang
  • 664
  • 1
  • 15
  • 25
  • `RGBCGColor` should be called `rgbCGColor`. I just spent like 2 minutes trying to find a class called `RGBCGColor` lol – Alexander Feb 24 '20 at 15:13
  • https://developer.apple.com/documentation/coregraphics/1455930-cgcolorgetcomponents?language=objc "The size of the array is one more than the number of components of the color space for the color." Might be different https://developer.apple.com/documentation/coregraphics/cgcolorspace/color_space_names, but since you are doing `CGColorSpaceCreateDeviceRGB`, you should get 4 (Red,Green,Bluee & alpha). – Larme Feb 24 '20 at 15:28
  • 1
    You should use UIColor method getWhite as shown in the same question https://stackoverflow.com/a/40062565/2303865 – Leo Dabus Feb 24 '20 at 15:53

0 Answers0