Working with Color
Colors 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:
- Device-dependent
Color spaces support colors that may appear differently on different devices (such as a color printer or monitor).
- Device-independent
Colors are calibrated so they appear the same on any output device.
- Named
Color spaces represent colors that don’t correspond to numerical values, but are referenced in a catalogue of named colors.
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.
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.
Get Cocoa in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.