albertski
albertski

Reputation: 2622

How to convert a UIColor to a black and white UIColor

I am setting the background color of my label, but I would like to have the color be the black and white UIColor instead of the original UIColor.

self.MyLabel.backgroundColor = self.selectedColors.color

Upvotes: 1

Views: 742

Answers (2)

Esmaeil
Esmaeil

Reputation: 658

By thanks of @Sam answer, I write an extension for UIColor:

extension UIColor {
    
    var grayScale: UIColor? {
        var white: CGFloat = 0
        var alpha: CGFloat = 0
        guard self.getWhite(&white, alpha: &alpha) else {
            return nil
        }
        return UIColor(white: white, alpha: alpha)
    }
}

You can use it like this:

var grayScaleColorOfRed = UIColor.red.grayScale ?? UIColor.grey

Upvotes: 1

Sam
Sam

Reputation: 3485

Looks like you'll need to convert your colour to grayscale.

While you can do this by averaging the R, G and B components of the colour, apple actually provide a nice method to grab the grayscale value:

func getWhite(_ white: UnsafeMutablePointer<CGFloat>?, 
    alpha: UnsafeMutablePointer<CGFloat>?) -> Bool

So to use this, you would first extract the grayscale colour and then init a new UIColor:

let originalColor = self.selectedColors.color

var white: CGFloat = 0
var alpha: CGFloat = 0
guard originalColor.getWhite(&white, alpha: &alpha) else {

    // The color couldn't be converted! Handle this unexpected error
    return
}

let newColor = UIColor(white: white, alpha: alpha)
self.MyLabel.backgroundColor = newColor

Upvotes: 3

Related Questions