Search code examples
iosswiftuicolor

UIColor: Is grayscale value a property?


https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIColor_Class/#//apple_ref/occ/clm/UIColor/blackColor

Creating a UIColor with Preset Component Values

+ blackColor

Returns a color object whose grayscale value is 0.0 and whose alpha value is 1.0.

Is there a method to retrieve a color objects "grayscale value"?


Solution

  • You can use the getWhite(_:alpha:) method on UIColor to effectively get the grayscale values.

    Playground example:

    import UIKit
    
    let piColor = UIColor(red: 0.31, green: 0.41, blue: 0.59, alpha: 1.0)
    var grayscale: CGFloat = 0
    var alpha: CGFloat = 0
    
    if piColor.getWhite(&grayscale, alpha: &alpha) {
        grayscale
        let grayscaleColor = UIColor(white: grayscale, alpha: alpha)
    }
    

    enter image description here