105

I'm creating a color object using the following code.

curView.backgroundColor = [[UIColor alloc] initWithHue:229 saturation:40 brightness:75 alpha:1];

How can I retrieve RGB values from the created color object?

JAL
  • 41,701
  • 23
  • 172
  • 300
defmech
  • 1,307
  • 2
  • 9
  • 14
  • possible duplicate of [Extracting rgb from UIColor](http://stackoverflow.com/questions/816828/extracting-rgb-from-uicolor) – Roddy Jun 28 '11 at 09:19
  • 5
    Just a note, the parameters passed into the method -initWithHue:saturation:brightness:alpha: should all be between 0.0 and 1.0. – geekinit Sep 04 '11 at 04:58
  • http://stackoverflow.com/questions/4700168/get-rgb-value-from-uicolor-presets/24203324#24203324 – Waseem Shah Jun 13 '14 at 10:36

16 Answers16

121

In iOS 5 you could use:

CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha =0.0;
[multipliedColor getRed:&red green:&green blue:&blue alpha:&alpha];
Teetotum
  • 1,899
  • 2
  • 16
  • 10
  • This is supported only in iOS 5.0 or newer. – Jon Trauntvein Dec 12 '11 at 15:14
  • 3
    Be warned that this method will only succeed if the starting color is in "a compatible color space", which can vary depending on the device/OS. For example I just discovered that calling this on [UIColor darkGrayColor] will fail on an iPad 2 running iOS 7. However the same color works fine on an iPad Air running iOS 8. – devios1 Feb 18 '15 at 22:38
  • @devios1 This can likely solved by first serializing the color then deserializing it using `NSKeyedArchiver`, like so: `multipliedColor = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject: multipliedColor]];` – Albert Renshaw Jul 27 '18 at 06:18
88
const CGFloat *colors = CGColorGetComponents( curView.backgroundColor.CGColor );

These links provide further details:

Pang
  • 9,564
  • 146
  • 81
  • 122
codelogic
  • 71,764
  • 9
  • 59
  • 54
  • Answer below should have been a comment. Oops. – defmech Jan 12 '09 at 22:36
  • 18
    Note: this only works for colors in the RGB space. For example, this will not work on [UIColor whiteColor] as that is not in RGB. – Jason Feb 15 '10 at 22:06
  • 2
    I posted some sample code in this question to get this working in non-RGB contexts: http://stackoverflow.com/questions/4700168/get-rgb-value-from-uicolor-presets – Jesse Rusak Jan 15 '11 at 15:28
  • 4
    If someone finding problem on how to get values from `colors`, you can write something like, `CGFloat red = colors[0];` – Hemang Jul 02 '14 at 09:49
  • `error: :3:1: error: 'CGColorGetComponents' has been replaced by property 'CGColor.components'` – pkamb Dec 07 '18 at 01:44
44

SWIFT 3 & 4

I found that cgColor.components would not always return 4 color values, so I changed this so it gets them from a CIColor wrapper

extension UIColor {
    var redValue: CGFloat{ return CIColor(color: self).red }
    var greenValue: CGFloat{ return CIColor(color: self).green }
    var blueValue: CGFloat{ return CIColor(color: self).blue }
    var alphaValue: CGFloat{ return CIColor(color: self).alpha }
}

SWIFT 2

extension UIColor {
    var red: CGFloat{ return CGColorGetComponents(self.CGColor)[0] }
    var green: CGFloat{ return CGColorGetComponents(self.CGColor)[1] }
    var blue: CGFloat{ return CGColorGetComponents(self.CGColor)[2] }
    var alpha: CGFloat{ return CGColorGetComponents(self.CGColor)[3] }
}

It's not the most efficient way so I wouldn't go using this where a view will be constantly re-drawn.

David Rees
  • 6,792
  • 3
  • 31
  • 39
11

Hopefully this will be helpful

CGFloat red, green, blue, alpha;

//Create a sample color

UIColor *redColor = [UIColor redColor];

//Call 

[redColor getRed: &red 
  green: &green
  blue: &blue 
  alpha: &alpha];
NSLog(@"red = %f. Green = %f. Blue = %f. Alpha = %f",
  red,
  green,
  blue,
  alpha);
drs
  • 5,679
  • 4
  • 42
  • 67
Ashok Kumar
  • 225
  • 4
  • 9
8

You can use CIColor components (swift 5)

let ciColor = CIColor(color: backgroundColor)
let alpha = ciColor.alpha
let red = ciColor.red
let blue = ciColor.blue
let green = ciColor.green

this works for non-RGB color space too

Mari
  • 109
  • 1
  • 3
7

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.

Geri Borbás
  • 15,810
  • 18
  • 109
  • 172
5
 UIColor *color = [[UIColor greenColor] retain]; //line 1

//OR(You will have color variable either like line 1 or line 2)

color = curView.backgroundColor;//line 2
CGColorRef colorRef = [color CGColor];

int _countComponents = CGColorGetNumberOfComponents(colorRef);

if (_countComponents == 4) {
    const CGFloat *_components = CGColorGetComponents(colorRef);
    CGFloat red     = _components[0];
    CGFloat green = _components[1];
    CGFloat blue   = _components[2];
    CGFloat alpha = _components[3];

    NSLog(@"%f,%f,%f,%f",red,green,blue,alpha);
}

[color release];
Girish
  • 4,692
  • 4
  • 35
  • 55
Linh Nguyen
  • 2,006
  • 1
  • 20
  • 16
5
const float* colors = CGColorGetComponents( curView.backgroundColor.CGColor );

Thanks. I had to add the const at the start of the line as it was generating a warning.

defmech
  • 1,307
  • 2
  • 9
  • 14
1

Since iOS 2.0 there is a private instance method on UIColor called styleString which returns an RGB or RGBA string representation of the color, even for colors like whiteColor outside the RGB space.

Objective-C:

@interface UIColor (Private)

- (NSString *)styleString;

@end

// ...

[[UIColor whiteColor] styleString]; // rgb(255,255,255)
[[UIColor redColor] styleString]; // rgb(255,0,0)
[[UIColor lightTextColor] styleString]; // rgba(255,255,255,0.600000)

In Swift you could use a bridging header to expose the interface. With pure Swift, you will need to create an @objc protocol with the private method, and unsafeBitCast UIColor with the protocol:

@objc protocol  UIColorPrivate {
    func styleString() -> String
}

let white = UIColor.whiteColor()
let red = UIColor.redColor()
let lightTextColor = UIColor.lightTextColor()

let whitePrivate = unsafeBitCast(white, UIColorPrivate.self)
let redPrivate = unsafeBitCast(red, UIColorPrivate.self)
let lightTextColorPrivate = unsafeBitCast(lightTextColor, UIColorPrivate.self)

whitePrivate.styleString() // rgb(255,255,255)
redPrivate.styleString() // rgb(255,0,0)
lightTextColorPrivate.styleString() // rgba(255,255,255,0.600000)
JAL
  • 41,701
  • 23
  • 172
  • 300
1

Swift 3 version of David Rees answer:

extension UIColor {

    var redValue: CGFloat{
        return cgColor.components! [0]
    }

    var greenValue: CGFloat{
        return cgColor.components! [1]
    }

    var blueValue: CGFloat{
        return cgColor.components! [2]
    }

    var alphaValue: CGFloat{
        return cgColor.components! [3]
    }
}
danfordham
  • 980
  • 9
  • 15
1

The top voted answer is outdated:

error: :3:1: error: 'CGColorGetComponents' has been replaced by property 'CGColor.components'

Instead, use

myUIColor.cgColor.components

pkamb
  • 33,281
  • 23
  • 160
  • 191
0

I wanted to get the background color of the UITableViewStyle "UITableViewStyleGrouped" so in the viewDidAppear: method I added the code:

NSLog(@"%@", self.tableView.backgroundView.backgroundColor);

It did what I anticipated and returned the log:

UIDeviceRGBColorSpace 0.937255 0.937255 0.956863 1

So in short just type in NSLog(@"%@", [UIColor whateverColor]);

Scott
  • 1,154
  • 1
  • 12
  • 25
0

Some useful macros I've made for this and other color controls:

In your case you would just use

getRGBA(myColor, red, green, blue, alpha);

NSLog(@"Red Value: %f", red);
NSLog(@"Blue Value: %f", green);
NSLog(@"Green Value: %f", blue);

Macros:

#define rgba(r,g,b,a) [UIColor colorWithRed:((float)(r))/255.0f green:((float)(g))/255.0f blue:((float)(b))/255.0f alpha:a]
#define rgb(r,g,b) rgba(r, g, b, 1.0f)

#define rgbaf(r,g,b,a) [UIColor colorWithRed:(r) green:(g) blue:(b) alpha:a]
#define rgbf(r,g,b) rgbaf(r, g, b, 1.0f)

#define rgba_fromColor(__color, __r, __g, __b, __a) \
CGFloat __r, __g, __b, __a;\
UIColor *__unpackedColor = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:__color]];/*Bring system colors into compatible color-space (e.g. DarkGrayColor)*/\
[__unpackedColor getRed:&__r green:&__g blue:&__b alpha:&__a];
#define getRGBA(__color, __r, __g, __b, __a) hsba_fromColor(__color, __r, __g, __b, __a)

#define getRed(__color)  (\
(^float (void){\
rgba_fromColor(__color, r, g, b, a);\
return r;\
})()\
)

#define getGreen(__color)  (\
(^float (void){\
rgba_fromColor(__color, r, g, b, a);\
return g;\
})()\
)

#define getBlue(__color)  (\
(^float (void){\
rgba_fromColor(__color, r, g, b, a);\
return b;\
})()\
)

#define getAlpha(__color)  (\
(^float (void){\
rgba_fromColor(__color, r, g, b, a);\
return a;\
})()\
)










#define hsba(h,s,b,a) [UIColor colorWithHue:((float)(h))/360.0f saturation:((float)(s))/100.0f brightness:((float)(b))/100.0f alpha:a]
#define hsb(h,s,b) hsba(h, s, b, 1.0f)

#define hsbaf(h,s,b,a) [UIColor colorWithHue:(h) saturation:(s) brightness:(b) alpha:a]
#define hsbf(h,s,b) rgbaf(h, s, b, 1.0f)

#define hsba_fromColor(__color, __h, __s, __b, __a) \
CGFloat __h, __s, __b, __a;\
UIColor *__unpackedColor = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:__color]];/*Bring system colors into compatible color-space (e.g. DarkGrayColor)*/\
[__unpackedColor getHue:&__h saturation:&__s brightness:&__b alpha:&__a];
#define getHSBA(__color, __h, __s, __b, __a) rgba_fromColor(__color, __h, __s, __b, __a)

#define getHue(__color)  (\
(^float (void){\
hsba_fromColor(__color, h, s, b, a);\
return h;\
})()\
)

#define getSaturation(__color)  (\
(^float (void){\
hsba_fromColor(__color, h, s, b, a);\
return s;\
})()\
)

#define getBrightness(__color)  (\
(^float (void){\
hsba_fromColor(__color, h, s, b, a);\
return b;\
})()\
)

/*
///already defined in RGBA macros
#define getAlpha(__color)  (\
(^float (void){\
hsba_fromColor(__color, h, s, b, a);\
return a;\
})()\
)
*/
Community
  • 1
  • 1
Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195
0

CGColor's property components is what you need.

The code below

UIColor.separator.cgColor.components

Prints the following

Optional([0.23529411764705882, 0.23529411764705882, 0.2627450980392157, 0.29])

Where the first element of the array is a red value, the second one is a green value, the third one is a blue value and the last one is an alpha value. Pretty simple!

devshok
  • 737
  • 1
  • 8
  • 19
  • I'd say this answer is wrong, as using `CGColor` would only work if `UIColor` initialization is based on red, green and blue components. On the other hand, creating a `CIColor` from `UIColor` gives you the ability to get the RGB components even if initialized with `UIColor(hue: saturation: brightness: alpha:)` or `UIColor(white: alpha:)`,... – Andrej Mar 23 '23 at 14:06
  • You're totally right. Thank you for your comment! @Andrej – devshok Apr 25 '23 at 21:14
-1

Using HandyUIKit makes this really easy:

import HandyUIKit    

let color = UIColor(red: 0.1, green: 0.2, blue: 0.3, alpha: 0.4)

// get any of the rgba values
color.rgba.red    // => 0.1
color.rgba.green  // => 0.2
color.rgba.blue   // => 0.3
color.rgba.alpha  // => 0.4

There is also a similar option to get hsba values:

let color = UIColor(hue: 0.1, saturation: 0.2, brightness: 0.3, alpha: 0.4)

// you can get any of the hsba values, too
color.hsba.hue         // => 0.1
color.hsba.saturation  // => 0.2
color.hsba.brightness  // => 0.3
color.hsba.alpha       // => 0.4

Simply install it using Carthage and you're good to go.

I hope it helps!

Jeehut
  • 20,202
  • 8
  • 59
  • 80
-6

set your UIColor like this

UIColor.FromRGB(128, 179, 255)

this is for Xamarin ios... but for sure there is a method like this in swift.

Daniel
  • 3,322
  • 5
  • 30
  • 40