Monday, June 13, 2011

How to get RGB values from UIColor ?


I am giving an example here where you take color either as the standard color given with Apple API or you can have color created and allocated with RGBA values.


      UIColor *color = [[UIColor greenColor] retain]; //line 1

    //OR(You will have color variable either like line 1 or line 2)
    
    color = [[UIColor alloc] initWithRed:0.5 green:0.2 blue:0 alpha:1];//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];


You have to make sure that before you extract the components out of UIColor, it should have retain count of 1. If not , then it will give error !

2 comments:

  1. I was hunting for a solution 20 minutes and everyone seems to be missing yours
    CGColorRef colorRef = [color CGColor];

    Thanks a lot!
    ripegooseberry

    ReplyDelete
  2. Is it possible vice-verse of it ? I have the RGB Can I convert it to Color string like Yellow, Green etc ?

    ReplyDelete