dontWatchMyProfile
dontWatchMyProfile

Reputation: 46330

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?

Upvotes: 4

Views: 1138

Answers (4)

leanne
leanne

Reputation: 8729

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
*/

Upvotes: 0

Geri Borb&#225;s
Geri Borb&#225;s

Reputation: 16608

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.

Upvotes: 0

Dan
Dan

Reputation: 1

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

Upvotes: 0

Vladimir
Vladimir

Reputation: 170849

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]);

Upvotes: 6

Related Questions