What does CGColorGetComponents() return?

2019-04-07 10:26发布

CGFloat* colors = CGColorGetComponents(hsbaColor.CGColor);

Does this return a float, or an array of floats? It looks like the asterisk is shorthand for creating an array. Is that correct?

When I call this function on the CGColor property of an HSB UIColor object does it convert the values to RGB?

5条回答
Melony?
2楼-- · 2019-04-07 10:56

Yes, it returns an array of CGFloats. Specifically, it returns "an array of intensity values for the color components (including alpha) associated with the specified color."

The color components returned depend on what color space the passed CGColorRef uses.

More information can be found in the CGColor documentation.

查看更多
Summer. ? 凉城
3楼-- · 2019-04-07 10:56

To get RGB components I use:

// Get UIColor's RGB normalized components (0..1)
CGFloat red, green, blue, alpha;
[color getRed:&red green:&green blue:&blue alpha:&alpha];

// Convert RGB components to 8-bit values (0..255)
int r = (int)(red * 255.0);
int g = (int)(green * 255.0);
int b = (int)(blue * 255.0);
查看更多
啃猪蹄的小仙女
4楼-- · 2019-04-07 11:00
CGFloat* colors = CGColorGetComponents(hsbaColor.CGColor);

Does this return a float, or an array of floats? It looks like the asterisk is shorthand for creating an array. Is that correct?

Sort of.

CGFloat *colors declares a variable holding a pointer to at least one CGFloat. CGColorGetComponents returns a pointer to several CGFloats, one after the other—a C array. You take that pointer and assign it to (put the pointer in) the colors variable.

Declaring the variable does not create the array. In fact, neither does CGColorGetComponents. Whatever created the CGColor object created the array and stored it inside the object; CGColorGetComponents lets you have the pointer to that storage.

Declaring the CGFloat *colors variable creates only a place—the variable—to store a pointer to one or more CGFloats. The thing in the variable is the pointer, and the thing at that pointer is the array.

If this is still unclear, see Everything you need to know about pointers in C.

查看更多
迷人小祖宗
5楼-- · 2019-04-07 11:04

Here's an example of how you can correctly convert a CGColorRef myColorRef to an NSColor myNSColor:

NSColorSpace *cp = [[NSColorSpace alloc] initWithCGColorSpace:CGColorGetColorSpace(myColorRef)];
const CGFloat *components = CGColorGetComponents(myColorRef);
size_t componentCount = CGColorGetNumberOfComponents(myColorRef);
NSColor* myNSColor = [NSColor colorWithColorSpace:cp components:components count:componentCount];
查看更多
等我变得足够好
6楼-- · 2019-04-07 11:09

From Apple:

It returns the values of the color components (including alpha) associated with a Quartz color. An array of intensity values for the color components (including alpha) associated with the specified color. The size of the array is one more than the number of components of the color space for the color.

查看更多
登录 后发表回答