Search code examples
iosuicolor

iOS convert a color to RGB


I have a function which receives a UIColor and needs to use it's RGBA values. What I did so far was to use CGColorGetComponents but that doesn't work well for other colorspaces (for example [UIColor blackColor] which is in grayscale). Using getRed green blue (in iOS 5) also doesn't work on [UIColor blackColor] (returns false).

Any easy way of doing this?


Solution

  • The following method should work in most cases (except pattern-colors). Add it as a category to UIColor.

    - (void)getRGBA:(CGFloat*)buffer {
            CGColorRef clr = [self CGColor];
            NSInteger n = CGColorGetNumberOfComponents(clr);
            const CGFloat *colors = CGColorGetComponents(clr);
            switch (n) {
            case 2:
                for(int i = 0; i<3; ++i){
                    buffer[i] = colors[0];
                }
                buffer[3] = CGColorGetAlpha(clr);
                break;
            case 3:
                for(int i = 0; i<3; ++i){
                    buffer[i] = colors[i];
                }
                buffer[3] = 1.0;
                break;
            case 4:
                for(int i = 0; i<4; ++i){
                    buffer[i] = colors[i];
                }
                break;
            default:
                break;
            }
    }