'How to access the color components of an UIColor?

i.e. I want to know the value of blue. How would I get that from an UIColor?



Solution 1:[1]

UIColor class does not provide information about color components. You must get components from its CGColor instead. Note that the number of components depends on color space used in CGColorRef.

This code prints components for blue color:

UIColor* color = [UIColor blueColor];
int n = CGColorGetNumberOfComponents(color.CGColor);
const CGFloat *coms = CGColorGetComponents(color.CGColor);
for (int i = 0; i < n; ++i)
    NSLog(@"%f", coms[i]);

Solution 2:[2]

I was just looking up this problem earlier this morning. I don't know why UIColor is so incomplete compared to NSColor. Anyway, I found this useful category for UIColor: Accessing UIColor Components

Solution 3:[3]

Just made a category for this.

NSLog(@"%f", [UIColor blueColor].blue); // 1.000000

Goes something like:

typedef enum { R, G, B, A } UIColorComponentIndices;

@implementation UIColor (EPPZKit)

-(CGFloat)red
{ return CGColorGetComponents(self.CGColor)[R]; }

-(CGFloat)green
{ return CGColorGetComponents(self.CGColor)[G]; }

-(CGFloat)blue
{ return CGColorGetComponents(self.CGColor)[B]; }

-(CGFloat)alpha
{ return CGColorGetComponents(self.CGColor)[A]; }

@end

Part of eppz!kit with more UIColor goodies.

Solution 4:[4]

Here's a Swift extension with computed property using UIColor's getRed(_:green:blue:alpha) method (available since iOS 5; and this code tested in Xcode 13.3 and iOS 12+)

extension UIColor {
    
    var rgbaComponents: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0
        
        getRed(&red, green: &green, blue: &blue, alpha: &alpha)

        return (red, green, blue, alpha)
    }

}

Example use:

let purple = UIColor.systemPurple
print("purple.cgColor: \(purple.cgColor)")

let components = purple.rgbaComponents
print("components: \(components)")

print("red: \(components.red)")
print("green: \(components.green)")
print("blue: \(components.blue)")
print("alpha: \(components.alpha)")

/* prints--
purple.cgColor: <CGColor 0x2813cafa0> [<CGColorSpace 0x2813d4060> (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; sRGB IEC61966-2.1; extended range)] ( 0.686275 0.321569 0.870588 1 )
components: (red: 0.6862745098039216, green: 0.3215686274509804, blue: 0.8705882352941177, alpha: 1.0)
red: 0.6862745098039216
green: 0.3215686274509804
blue: 0.8705882352941177
alpha: 1.0
*/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vladimir
Solution 2 Dan
Solution 3 Geri Borbás
Solution 4 leanne