NSColor object stores color data and sometimes opacity (alpha value). Many methods in AppKit require you to specify color data using a
NSColor object; when drawing you use them to set the current fill and stroke colors. Color objects are immutable and can be used safely from multiple threads in your app.
- macOS 10.0+
NSColor objects can be created in a variety of ways:
AppKit provides standard system colors that you can use to match the colors of your own UI objects to those provided by AppKit. You can use these colors without needing to understand the underlying representation of color.
AppKit provides definitions for very basic colors, such as red, orange, yellow, and so on.
You can create a custom color in a variety of color spaces.
You can create a color object from another object, such as another
NSColorobject, a Core Graphics representation of a color, or a Core Image color.
You can create a color from a
NSImageobject, which is used to paint a repeating pattern instead of a solid color.
You can create a color by applying a transform to another
NSColorobject. For example, you might perform a blend operation between two colors, or you might create a color that represents the same color, but in a different color space.
Color and Color Spaces
NSColor object is typically represented internally as a Core Graphics color (
CGColor) in a Core Graphics color space (
CGColor). There are methods and properties that return the underlying color data. See Retrieving Component Values from an NSColor object and Retrieving Individual Components.
It is invalid to use an accessor method related to components of a particular color space on an
NSColor object that does not share the same color space model. For example, the
red property and
get method work on color objects that use an RGB color spaces model. If you send such a message to an
NSColor object in the CMYK color space, an exception is raised. Further, the
get method and
number property work in color spaces that have individual components. Thus they return the components of
NSColor objects as individual floating-point values regardless of whether they’re based on
NSColor objects or named color spaces. However, older component-fetching methods such as
get are only effective on
NSColor objects based on named color spaces.
If you have an
NSColor object in an unknown color space and you want to extract its components, you should first convert the color object to a known color space before using the component accessor methods of that color space.