Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to get RGBA Color Components from UIColor?

Is there a quicker (or better) way to get the [RGBA] color components from UIColor? There seem to be a lot of variations of this around (some on here, all essentially similar to what I have done here) I am just curious if there is an alternative as it seems a bit "lacking" given that everything else is usually so complete and well thought out.

if([eachKey isEqualToString:@"NSColor"]) {
    UIColor *newColor = [attrs valueForKey:eachKey];
    //NSLog(@"COLOR: %@", newColor);
    CGColorRef colorRef = [newColor CGColor];
    //NSLog(@"%@", colorRef);
    int numComponets = CGColorGetNumberOfComponents(colorRef);
    if(numComponets == 4) {
        const CGFloat *components = CGColorGetComponents(colorRef);
        CGFloat compR = components[0];
        CGFloat compG = components[1];
        CGFloat compB = components[2];
        CGFloat compA = components[3];

        //NSLog(@"R:%f G:%f B:%f, A:%f", compR, compG, compB, compA);
    }
}

I am not looking for how (I think I have the long version above) I would just like to know if this is the way your supposed to do this now?

like image 587
fuzzygoat Avatar asked Jun 28 '12 16:06

fuzzygoat


People also ask

How do I get RGB values from UIColor Swift?

let swiftColor = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1) println("RGB Value is:"); println(swiftColor.

What is CGColor in Swift?

CGColor is the fundamental data type used internally by Core Graphics to represent colors. CGColor objects, and the functions that operate on them, provide a fast and convenient way of managing and setting colors directly, especially colors that are reused (such as black for text).


2 Answers

CGFloat r, g, b, a;    
[MyColor getRed: &r green:&g blue:&b alpha:&a];

iOS 5+ required.

like image 52
Seva Alekseyev Avatar answered Nov 27 '22 10:11

Seva Alekseyev


Check this method in the class reference.

like image 24
Garoal Avatar answered Nov 27 '22 10:11

Garoal