[ Team LiB ] |
4.6 Working with ColorColors in the Application Kit are represented by instances of the NSColor class, which provides an interface for creating colors and setting the color used by the current graphics context. AppKit supports several color spaces that fall into three categories:
The six color spaces supported by the Application Kit are based on these three categories, as detailed in Table 4-3.
The color spaces that are NSDevice... are device-dependent color spaces, while those that are NSCalibrated... color spaces are device-independent. Table 4-3 lists constant names defined by AppKit to identify color spaces in code. To create an instance of NSColor, use any colorWith... class method that takes component values for the color spaces indicated by the method name, such as colorWithCalibratedRed:green:blue:alpha. The parameters passed to these methods as component values are floats ranging between 0 and 1. Values that fall below 0 are interpreted as black, and those above 1 are interpreted as the pure color. Several class methods are also named after colors, such as redColor and blueColor. These methods return an instance of NSColor whose components are set for the specified color and whose color space is NSCalibratedRGBColorSpace. Example 4-7 shows different ways to create color objects. Example 4-7. Various ways to create color objectsNSColor *c; // Apple-menu blue in RGB colorspaces c = [NSColor colorWithCalibratedRed:0.243 green:0.505 blue:0.863 alpha:1.0]; // Same color in CMYK colorspace c = [NSColor colorWithDeviceCyan:0.76 magenta:0.50 yellow:0.14 black:0.0 alpha:1.0]; NSColor's set method sets the receiver as the current graphics context's color. All subsequent drawing is done in the color that was last set. By default, all drawing is done in black. Example 4-8 demonstrates how this is done in a drawRect: method. Example 4-8. Setting the color of a graphics context and rendering a path- (void)drawRect:(NSRect)rect { // Construct path [[NSColor greyColor] set]; [bp fill]; [[NSColor blackColor] set]; [bp stroke]; } |
[ Team LiB ] |