Best way to get RGBA Color Components from UIColor?

Is there a faster (or better) way to get color components [RGBA] from UIColor? It seems that there are many variations of this (some here, in fact, are similar to what I did here). I am just wondering if there is an alternative, as this seems a bit "missing", given that everything else is usually so complete and 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'm not looking for how (I think I have a long version above). I just would like to know if this is how you expected to do it now?

+6
source share
3 answers
 CGFloat r, g, b, a; [MyColor getRed: &r green:&g blue:&b alpha:&a]; 
Is required

iOS 5+.

+16
source

Check this method in the class reference.

+2
source
 - (BOOL)getRed:(CGFloat *)red green:(CGFloat *)green blue:(CGFloat *)blue alpha:(CGFloat *)alpha 

The method above is not reliable; it will return NO for [UIColor whiteColor] (or another shade of gray).

Using

if(numComponets == 5) {

instead

if(numComponets == 4) {

From api doc:

 The size of the array is one more than the number of components of the color space for the color. 
+1
source

Source: https://habr.com/ru/post/919263/


All Articles