NSImage Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/AppKit.framework
Availability
Available in OS X v10.0 and later.
Companion guide
Declared in
NSGraphics.h
NSImage.h
Related sample code

Overview

The NSImage class is a high-level interface for manipulating image data. You use instances of this class to load existing images, create new images, and draw the resulting image data into your views. Although you use this class predominantly for image-related operations, the class itself knows little about the underlying image data. Instead, it works in conjunction with one or more image representation objects (subclasses of NSImageRep) to manage and render the image data. For the most part, these interactions are transparent.

The NSImage class serves many purposes, providing support for the following tasks:

The NSImage class itself is capable of managing image data in a variety of formats. The specific list of formats is dependent on the version of the operating system but includes many standard formats such as TIFF, JPEG, GIF, PNG, and PDF among others. Each format is managed by a specific type of image representation object, whose job is to manage the actual image data. You can get a list of supported formats using the methods described in “Determining the Supported Image Types.”

For more information about how to use image objects in your app, see Cocoa Drawing Guide.

Using Images with CALayer Objects

Although you can assign an NSImage object directly to the contents property of a CALayer object, doing so may not always yield the best results. Instead of using your image object, you can use the layerContentsForContentsScale: method to obtain an object that you can use for your layer’s contents. That method creates an image that is suited for use as the contents of a layer and that is supports all of the layer’s gravity modes. By contrast, the NSImage class supports only the kCAGravityResize, kCAGravityResizeAspect, and kCAGravityResizeAspectFill modes.

Before calling the layerContentsForContentsScale: method, use the recommendedLayerContentsScale: method to get the recommended scale factor for the resulting image. Listing 1 shows a typical example that uses the scale factor of a window’s backing store as the desired scale factor. From that scale factor, the code gets the recommended scale factor for the specified image object and creates an object that can be assigned to the layer. You might use this code for images that fit the layer bounds precisely or for which you rely on the contentsGravity property of the layer to position or scale the image.

Listing 1  Assigning an image to a layer

static void updateLayerWithImageInWindow1(NSImage *image, CALayer *layer, NSWindow *window) {
   CGFloat desiredScaleFactor = [window backingScaleFactor];
   CGFloat actualScaleFactor = [image recommendedLayerContentsScale:desiredScaleFactor];
 
   id layerContents = [image layerContentsForContentsScale:actualScaleFactor];
 
   [layer setContents:layerContents];
   [layer setContentsScale:actualScaleFactor];
}

Tasks

Initializing a New NSImage Object

Referring to Images by Name

Setting the Image Attributes

Determining the Supported Image Types

Working With Image Representations

Setting the Image Representation Selection Criteria

Drawing the Image

Managing the Drawing Options

Managing the Focus

Working With Alignment Metadata

Managing the Caching Options

Accessing the Delegate

Producing TIFF Data for the Image

Producing a CGImage from an Image

Managing Incremental Loads

Hit Testing an Image

Managing Image Accessibility

Using an Image with Core Animation

Managing Axis Matching

Deprecated Methods

Class Methods

canInitWithPasteboard:

Tests whether the receiver can create an instance of itself using pasteboard data.

+ (BOOL)canInitWithPasteboard:(NSPasteboard *)pasteboard
Parameters
pasteboard

The pasteboard containing the image data.

Return Value

YES if the receiver knows how to handle the data on the pasteboard; otherwise, NO.

Discussion

This method uses the NSImageRep class method imageUnfilteredPasteboardTypes to find a class that can handle the data in the specified pasteboard. If you create your own NSImageRep subclasses, override the imageUnfilteredPasteboardTypes method to notify NSImage of the pasteboard types your class supports.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

imageFileTypes

Returns an array of strings identifying the image types supported by the registered NSImageRep objects.

+ (NSArray *)imageFileTypes
Return Value

An array of NSString objects, each of which identifies a single supported file type. The array can include encoded HFS file types as well as filename extensions.

Discussion

This list includes all file types supported by registered subclasses of NSImageRep plus those that can be converted to a supported type by a user-installed filter service. You can pass the array returned by this method directly to the runModalForTypes: method of NSOpenPanel.

Do not override this method. If your app supports custom image types, create and register an NSImageRep subclass that handles those types.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

imageNamed:

Returns the image object associated with the specified name.

+ (id)imageNamed:(NSString *)name
Parameters
name

The name associated with the desired image. This can be a name you assigned to the image or the name of an image file in your app bundle.

Return Value

The NSImage object associated with the specified name or nil if no such image was found.

Discussion

This method searches for named images in several places, returning the first image it finds matching the given name. The order of the search is as follows:

  1. Search for an object whose name was set explicitly using the setName: method and currently resides in the image cache.

  2. Search the app's main bundle for a file whose name matches the specified string. (For information on how the bundle is searched, see ““Accessing a Bundle's Contents”“ in Bundle Programming Guide.)

  3. Search the Application Kit framework for a shared image with the specified name.

When looking for files in the app bundle, it is better (but not required) to include the filename extension in the name parameter. When naming an image with the setName: method, it is convention not to include filename extensions in the names you specify. That way, you can easily distinguish between images you have named explicitly and those you want to load from the app's bundle.

One particularly useful image you can retrieve is your app's icon. This image is set by Cocoa automatically and accessible using the NSImageNameApplicationIcon constant. Icons for other apps can be obtained through the use of methods declared in the NSWorkspace class. You can also retrieve many of the standard system images using Cocoa defined constants; for more information, see the “Image Template Constants,” “Sharing Permissions Named Images,” “System Entity Images,” “Toolbar Named Images,” and “View Type Template Images” sections for applicable constants.

If an app is linked in Mac OS X v10.5 or later, images requested using this method and whose name ends in the word “Template” are automatically marked as template images.

The NSImage class may cache a reference to the returned image object for performance in some cases. However, the class holds onto cached objects only while the object exists. If all strong references to the image are subsequently removed, the object may be quietly removed from the cache. Thus, if you plan to hold onto a returned image object, you must maintain a strong reference to it like you would any Cocoa object. You can clear an image object from the cache explicitly by calling the object’s setName: method and specifying nil for the image name.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

imagePasteboardTypes

Returns an array of strings identifying the pasteboard types supported directly by the registered image representation objects.

+ (NSArray *)imagePasteboardTypes
Return Value

An array of NSString objects, each of which identifies a single supported pasteboard type. By default, this list contains the NSPDFPboardType, NSPICTPboardType, NSPostScriptPboardType, and NSTIFFPboardType types.

Discussion

This list includes all pasteboard types supported by registered subclasses of NSImageRep plus those that can be converted to a supported type by a user-installed filter service.

Do not override this method. Instead, override the imageUnfilteredPasteboardTypes method to notify NSImage of the pasteboard types your class supports.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

imageTypes

Returns an array of UTI strings identifying the image types supported by the registered NSImageRep objects, either directly or through a user-installed filter service.

+ (NSArray *)imageTypes
Return Value

An array of NSString objects, each of which contains a UTI identifying a supported image type. Some sample image-related UTI strings include "public.image”, "public.jpeg”, and "public.tiff”. For a list of supported types, see UTCoreTypes.h.

Discussion

The returned list includes UTIs all file types supported by registered subclasses of NSImageRep plus those that can be converted to a supported type by a user-installed filter service. You can use the returned UTI strings with any method that supports UTIs.

Do not override this method directly. If your app supports custom image types, create and register an NSImageRep subclass that handles those types.

Availability
  • Available in OS X v10.5 and later.
Declared In
NSImage.h

imageUnfilteredFileTypes

Returns an array of strings identifying the file types supported directly by the registered image representation objects.

+ (NSArray *)imageUnfilteredFileTypes
Return Value

An array of NSString objects, each of which identifies a single supported file type. File types are identified by file extension and HFS file types.

Discussion

The returned list does not contain pasteboard types that are available only through a user-installed filter service.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

imageUnfilteredPasteboardTypes

Returns an array of strings identifying the pasteboard types supported directly by the registered image representation objects.

+ (NSArray *)imageUnfilteredPasteboardTypes
Return Value

An array of NSString objects, each of which identifies a single supported pasteboard type.

Discussion

The returned list does not contain pasteboard types that are supported only through a user-installed filter service.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

imageUnfilteredTypes

Returns an array of UTI strings identifying the image types supported directly by the registered image representation objects.

+ (NSArray *)imageUnfilteredTypes
Return Value

An array of NSString objects, each of which contains a UTI identifying a supported image type. Some sample image-related UTI strings include "public.image”, "public.jpeg”, and "public.tiff”. For a list of supported types, see UTCoreTypes.h.

Discussion

The returned list includes UTI strings only for those file types that are supported directly by registered subclasses of NSImageRep. It does not include types that are supported through user-installed filter services. You can use the returned UTI strings with any method that supports UTIs.

Do not override this method directly. If your app supports custom image types, create and register an NSImageRep subclass that handles those types.

Availability
  • Available in OS X v10.5 and later.
See Also
Related Sample Code
Declared In
NSImage.h

imageWithSize:flipped:drawingHandler:

Creates and returns an image object whose contents are drawn using the specified block.

+ (id)imageWithSize:(NSSize)size flipped:(BOOL)drawingHandlerShouldBeCalledWithFlippedContext drawingHandler:(BOOL (^)(NSRect dstRect))drawingHandler
Parameters
size

The size of the image, measured in points.

drawingHandlerShouldBeCalledWithFlippedContext

YES to apply a flip transformation to the graphics context before drawing or NO to draw using the default Cocoa coordinate system orientation.

drawingHandler

A block that draws the contents of the image representation. This block is copied and stored by the underlying image representation object for later use. It is not executed until you draw the image. Because the block is executed later, it is executed on the same thread on which you draw the image itself, which can be any thread of your app. Therefore, the block must be safe to call from any thread. The block takes the following parameter:

dstRect

The destination rectangle in which to draw. The coordinates of this rectangle are specified in points.

The block returns a Boolean that indicates whether it drew the image successfully. Return YES from your block if it successfully drew the contents or NO if it did not.

Return Value

An initialized NSImage object or nil if the object could not be initialized.

Discussion

Use this method to generate an image that is correct at any resolution. This method creates an image object with a single NSCustomImageRep object to manage drawing. The image representation uses the block in the drawingHandler parameter to do the actual drawing.

When you draw the image for the first time, the underlying image representation executes the drawingHandler block. The image object caches the results according to its usual caching policies; see the cacheMode method. As long as the configuration of the destination graphics context does not change in a significant way, subsequent attempts to draw the image reuse the cached results whenever possible. If the pixel density or color space of the destination graphics context changes, though, the image representation throws away any caches and executes the block again to obtain a new version of the image. For example, if you originally drew the image on a standard resolution display but then draw it on a Retina display, the block is executed again to obtain an image at the new resolution.

The most typical use for this method is to create an image based on vector-based content. In that case, your drawingHandler block would redraw its existing path objects when asked. If you draw a mixture of vectors and images, you need to do more work to ensure that your images are the appropriate resolution for the destination graphics context.

Availability
  • Available in OS X v10.8 and later.
Declared In
NSImage.h

Instance Methods

accessibilityDescription

Returns the image’s accessibility description.

- (NSString *)accessibilityDescription
Return Value

A short localized string that does not include the name of the interface element.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSImage.h

addRepresentation:

Adds the specified image representation object to to the receiver.

- (void)addRepresentation:(NSImageRep *)imageRep
Parameters
imageRep

The image representation to add.

Discussion

After invoking this method, you may need to explicitly set features of the new image representation, such as the size, number of colors, and so on. This is true particularly when the NSImage object has multiple image representations to choose from. See NSImageRep and its subclasses for the methods you use to complete initialization.

Any representation added by this method is retained by the receiver. Image representations cannot be shared among multiple NSImage objects.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

addRepresentations:

Adds an array of image representation objects to the receiver.

- (void)addRepresentations:(NSArray *)imageReps
Parameters
imageReps

An array of NSImageRep objects.

Discussion

After invoking this method, you may need to explicitly set features of the new image representations, such as their size, number of colors, and so on. This is true particularly when the NSImage object has multiple image representations to choose from. See NSImageRep and its subclasses for the methods you use to complete initialization.

Representations added by this method are retained by the receiver. Image representations cannot be shared among multiple NSImage objects.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

alignmentRect

Returns alignment metadata that your code can use to position the image during layout.

- (NSRect)alignmentRect
Return Value

A rectangle containing the layout information for the image. If not set, the returned rectangle has an origin of (0, 0) and a size that matches the size of the image.

Discussion

The returned rectangle is merely a hint that your own code can use to determine positioning. The NSImage class does not use this rectangle during drawing. However, instances of NSCell typically use this information when laying out images within their own boundaries.

Availability
  • Available in OS X v10.5 and later.
Declared In
NSImage.h

backgroundColor

Returns the background color of image.

- (NSColor *)backgroundColor
Return Value

The background color of the image. The default color is transparent, as returned by the clearColor method of NSColor.

Discussion

The background color is visible only if the drawn image representation does not completely cover all of the pixels available for the image's current size.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

bestRepresentationForRect:context:hints:

Returns the best representation of the image for the specified rect using the provided hints.

- (NSImageRep *)bestRepresentationForRect:(NSRect)rect context:(NSGraphicsContext *)referenceContext hints:(NSDictionary *)hints
Parameters
rect

The area of the image to return.

referenceContext

A graphics context. This value can be nil.

hints

An optional dictionary of hints that provide more context for selecting or generating a CGImage, and may override properties of the referenceContext. See “Image Hint Dictionary Keys” for a summary of the possible key-value pairs.

Return Value

The image representation that most closely matches the specified criteria.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSImage.h

cacheMode

Returns the receiver’s caching mode.

- (NSImageCacheMode)cacheMode
Return Value

A value indicating the caching mode. For a list of possible values, see NSImageCacheMode. This value is set to NSImageCacheDefault by default.

Availability
  • Available in OS X v10.2 and later.
Declared In
NSImage.h

cancelIncrementalLoad

Cancels the current download operation immediately, if the image is being incrementally loaded.

- (void)cancelIncrementalLoad
Discussion

This call has no effect if the image is not loading.

Availability
  • Available in OS X v10.2 and later.
Declared In
NSImage.h

CGImageForProposedRect:context:hints:

Returns a CGImage capturing the drawing of the receiver.

- (CGImageRef)CGImageForProposedRect:(NSRect *)proposedDestRect context:(NSGraphicsContext *)referenceContext hints:(NSDictionary *)hints
Parameters
proposedDestRect

On input, the proposed destination rectangle for drawing the image. If NULL, it defaults to the smallest pixel-integral rectangle containing {{0,0}, [self size]}. The proposedDestRect is in user space in the reference context.

referenceContext

A graphics context.

hints

A dictionary of hints that provide more context for selecting or generating a CGImage, and may override properties of the referenceContext.

Return Value

A CGImageRef. This may be an existing CGImage if one is available. If not, a new CGImage is created.

Discussion

An NSImage is potentially resolution independent, and may have representations that allow it to draw well in many contexts. A CGImage is more like a single pixel-based representation. This method produces a snapshot of how the NSImage would draw if it was asked to draw in the proposed rectangle in the graphics context.

All input parameters are optional. They provide hints for how to choose among existing CGImages, or how to create one if there isn't already a CGImage available. The parameters are only hints.

This method is typically called, not overridden.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSImage.h

delegate

Returns the delegate object of the receiver

- (id < NSImageDelegate >)delegate
Return Value

The current delegate object, or nil if no delegate has been set.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

drawAtPoint:fromRect:operation:fraction:

Draws all or part of the image at the specified point in the current coordinate system.

- (void)drawAtPoint:(NSPoint)point fromRect:(NSRect)srcRect operation:(NSCompositingOperation)op fraction:(CGFloat)delta
Parameters
point

The location in the current coordinate system at which to draw the image.

srcRect

The source rectangle specifying the portion of the image you want to draw. The coordinates of this rectangle are specified in the image's own coordinate system. If you pass in NSZeroRect, the entire image is drawn.

op

The compositing operation to use when drawing the image. See the NSCompositingOperation constants.

delta

The opacity of the image, specified as a value from 0.0 to 1.0. Specifying a value of 0.0 draws the image as fully transparent while a value of 1.0 draws the image as fully opaque. Values greater than 1.0 are interpreted as 1.0.

Discussion

The image content is drawn at its current resolution and is not scaled unless the CTM of the current coordinate system itself contains a scaling factor. The image is otherwise positioned and oriented using the current coordinate system.

Unlike the compositeToPoint:fromRect:operation: and compositeToPoint:fromRect:operation:fraction: methods, this method checks the rectangle you pass to the srcRect parameter and makes sure it does not lie outside the image bounds.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

drawInRect:

Draws the image in the specified rectangle.

- (void)drawInRect:(NSRect)rect
Parameters
rect

The rectangle in which to draw the image, specified in the current coordinate system.

Discussion

This method draws the entire image in the specified rectangle, scaling the image as needed. The method composites the image using the NSCompositeSourceOver operation

Availability
  • Available in OS X v10.9 and later.
Declared In
NSImage.h

drawInRect:fromRect:operation:fraction:

Draws all or part of the image in the specified rectangle in the current coordinate system.

- (void)drawInRect:(NSRect)dstRect fromRect:(NSRect)srcRect operation:(NSCompositingOperation)op fraction:(CGFloat)delta
Parameters
dstRect

The rectangle in which to draw the image, specified in the current coordinate system.

srcRect

The source rectangle specifying the portion of the image you want to draw. The coordinates of this rectangle must be specified using the image's own coordinate system. If you pass in NSZeroRect, the entire image is drawn.

op

The compositing operation to use when drawing the image. See the NSCompositingOperation constants.

delta

The opacity of the image, specified as a value from 0.0 to 1.0. Specifying a value of 0.0 draws the image as fully transparent while a value of 1.0 draws the image as fully opaque. Values greater than 1.0 are interpreted as 1.0.

Discussion

If the srcRect and dstRect rectangles have different sizes, the source portion of the image is scaled to fit the specified destination rectangle. The image is otherwise positioned and oriented using the current coordinate system.

Unlike the compositeToPoint:fromRect:operation: and compositeToPoint:fromRect:operation:fraction: methods, this method checks the rectangle you pass to the srcRect parameter and makes sure it does not lie outside the image bounds.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

drawInRect:fromRect:operation:fraction:respectFlipped:hints:

Draws all or part of the image in the specified rectangle respecting the flippedness and hints.

- (void)drawInRect:(NSRect)dstSpacePortionRect fromRect:(NSRect)srcSpacePortionRect operation:(NSCompositingOperation)op fraction:(CGFloat)requestedAlpha respectFlipped:(BOOL)respectContextIsFlipped hints:(NSDictionary *)hints
Parameters
dstSpacePortionRect

The rectangle in which to draw the image, specified in the current coordinate system.

srcSpacePortionRect

The source rectangle specifying the portion of the image you want to draw. The coordinates of this rectangle must be specified using the image's own coordinate system. If you pass in NSZeroRect, the entire image is drawn.

op

The compositing operation to use when drawing the image. See the NSCompositingOperation constants.

requestedAlpha

The alpha of the image, specified as a value from 0.0 to 1.0. Specifying a value of 0.0 draws the image as fully transparent while a value of 1.0 draws the image as fully opaque. Values greater than 1.0 are interpreted as 1.0.

respectContextIsFlipped

YES if the drawing should respect the context flipped state, otherwise NO.

hints

An optional dictionary of hints that provide more context for selecting or generating the image. See “Image Hint Dictionary Keys” for a summary of the possible key-value pairs.

Discussion

If the srcSpacePortionRect and dstSpacePortionRect rectangles have different sizes, the source portion of the image is scaled to fit the specified destination rectangle.

Availability
  • Available in OS X v10.6 and later.
Related Sample Code
Declared In
NSImage.h

drawRepresentation:inRect:

Draws the image using the specified image representation object.

- (BOOL)drawRepresentation:(NSImageRep *)imageRep inRect:(NSRect)dstRect
Parameters
imageRep

The image representation object to be drawn.

dstRect

The rectangle in which to draw the image representation, specified in the current coordinate system.

Return Value

YES if the image was successfully drawn; otherwise, returns NO.

Discussion

This method fills the specified rectangle with the image's current background color and then sends a message to the specified image representation asking if to draw itself. If the image supports the ability to scale itself when it is resized, this method sends a drawInRect: message; otherwise, it sends a drawAtPoint: message.

You should not call this method directly; an NSImage object uses it to cache and print its image representations. You can override this method to change the way images are rendered into their caches and onto the printed page. For example, you could scale or rotate the coordinate system before sending this message to super to continue rendering the image representation.

If the background color is fully transparent and the image data is not being cached, the specified rectangle is not to be filled before the representation draws.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

hitTestRect:withImageDestinationRect:context:hints:flipped:

Returns whether the destination rectangle would intersect a non-transparent portion of the image.

- (BOOL)hitTestRect:(NSRect)testRectDestSpace withImageDestinationRect:(NSRect)imageRectDestSpace context:(NSGraphicsContext *)referenceContext hints:(NSDictionary *)hints flipped:(BOOL)flipped
Parameters
testRectDestSpace

The rectangle to hit test.

imageRectDestSpace

A rectangle representing the drawn size of the image.

referenceContext

A graphics context. This value can be nil.

hints

An optional dictionary of hints that provide more context for selecting or generating a CGImage, and may override properties of the referenceContext. See “Image Hint Dictionary Keys” for a summary of the possible key-value pairs.

flipped

YES if the image is flipped, otherwise NO.

Return Value

YES if the testRectDestSpace intersects with non-transparent content within the imageRectDestSpace, otherwise NO.

Discussion

This method simulates the results of hit-testing the test rectangle as if the image was drawn in the graphics context using the provided hints and respecting the specified flippedness.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSImage.h

initByReferencingFile:

Initializes and returns an image object using the specified file.

- (id)initByReferencingFile:(NSString *)filename
Parameters
filename

A full or relative path name specifying the file with the desired image data. Relative paths must be relative to the current working directory.

Return Value

An initialized NSImage object or nil if the new object cannot be initialized.

Discussion

This method initializes the image object lazily. It does not actually open the specified file or create any image representations from its data until an app attempts to draw the image or request information about it.

The filename parameter should include the file extension that identifies the type of the image data. The mechanism that actually creates the image representation for filename looks for an NSImageRep subclass that handles that data type from among those registered with NSImage.

Because this method doesn’t actually create image representations for the image data, your app should do error checking before attempting to use the image; one way to do so is by invoking the isValid method to check whether the image can be drawn.

This method invokes setDataRetained: with an argument of YES, thus enabling it to hold onto its filename. When archiving an image created with this method, only the image's filename is written to the archive.

If the cached version of the image uses less memory than the original image data, the original data is flushed and the cached image is used. (This can occur for images whose resolution is greater than 72 dpi.) If you resize the image by less than 50%, the data is loaded in again from the file. If you expect the file to change or be deleted, you should use initWithContentsOfFile: instead.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

initByReferencingURL:

Initializes and returns an image object using the specified URL.

- (id)initByReferencingURL:(NSURL *)url
Parameters
url

The URL identifying the image.

Return Value

An initialized NSImage object or nil if the new object cannot be initialized.

Discussion

This method initializes the image object lazily. It does not attempt to retrieve the data from the specified URL or create any image representations from that data until an app attempts to draw the image or request information about it.

This url parameter should include a file extension that identifies the type of the image data. The mechanism that actually creates the image representation looks for an NSImageRep subclass that handles that data type from among those registered with NSImage.

Because this method doesn’t actually create image representations for the image data, your app should do error checking before attempting to use the image; one way to do so is by invoking the isValid method to check whether the image can be drawn.

This method invokes setDataRetained: with an argument of YES, thus enabling it to hold onto its URL. When archiving an image created with this method, only the image's URL is written to the archive.

Availability
  • Available in OS X v10.2 and later.
Declared In
NSImage.h

initWithCGImage:size:

Initializes and returns an image object using the contents of a Core Graphics image.

- (id)initWithCGImage:(CGImageRef)cgImage size:(NSSize)size
Parameters
cgImage

The source CGImage.

size

The size of the new image. If size is NSZeroSize, the pixel dimensions of cgImage are assumed as the image’s size.

Return Value

An initialized NSImage object or nil if the new object cannot be initialized.

Discussion

You should not assume anything about the image, other than that drawing it is equivalent to drawing the CGImage.

This is not a designated initializer.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSImage.h

initWithContentsOfFile:

Initializes and returns an image object with the contents of the specified file.

- (id)initWithContentsOfFile:(NSString *)filename
Parameters
filename

A full or relative path name specifying the file with the desired image data. Relative paths must be relative to the current working directory.

Return Value

An initialized NSImage object or nil if the method cannot create an image representation from the contents of the specified file.

Discussion

Unlike initByReferencingFile:, which initializes an NSImage object lazily, this method immediately opens the specified file and creates one or more image representations from its data.

The filename parameter should include the file extension that identifies the type of the image data. This method looks for an NSImageRep subclass that handles that data type from among those registered with NSImage.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

initWithContentsOfURL:

Initializes and returns an image object with the contents of the specified URL.

- (id)initWithContentsOfURL:(NSURL *)aURL
Parameters
aUrl

The URL identifying the image.

Return Value

An initialized NSImage object or nil if the method cannot create an image representation from the contents of the specified URL.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

initWithData:

Initializes and returns an image object using the provided image data.

- (id)initWithData:(NSData *)data
Parameters
data

The data object containing the image data. The data can be in any format that OS X supports, including PDF, PICT, EPS, or any number of bitmap data formats.

Return Value

An initialized NSImage object or nil if the method cannot create an image representation from the contents of the specified data object.

Discussion

Use this method in cases where you already have image data in a supported format and want to obtain an NSImage object that represents that data. This method initializes the object with an image representation that is most appropriate for the type of data you provided.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

initWithDataIgnoringOrientation:

Initializes and returns an image object using the provided image data and ignoring the EXIF orientation tags.

- (id)initWithDataIgnoringOrientation:(NSData *)data
Parameters
data

The data object containing the image data. The data can be in any format that OS X supports, including PDF, PICT, EPS, or any number of bitmap data formats.

Return Value

An initialized NSImage object or nil if the method cannot create an image representation from the contents of the specified data object.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSImage.h

initWithIconRef:

Initializes the image object with a Carbon-style icon resource.

- (id)initWithIconRef:(IconRef)iconRef
Parameters
iconRef

A reference to a Carbon icon resource.

Return Value

An initialized NSImage object.

Discussion

Creates one or more bitmap image representations, one for each size icon contained in the IconRef data structure. This initialization method automatically retains the data in the iconRef parameter and loads the bitmaps from that data file lazily.

Availability
  • Available in OS X v10.5 and later.
Declared In
NSImage.h

initWithPasteboard:

Initializes and returns an image object with data from the specified pasteboard.

- (id)initWithPasteboard:(NSPasteboard *)pasteboard
Parameters
pasteboard

The pasteboard containing the image data. The data on the pasteboard can be in any format that OS X supports, including PDF, PICT, EPS, or any number of bitmap data formats.

Return Value

An initialized NSImage object or nil if the method cannot create an image from the contents of the pasteboard.

Discussion

The specified pasteboard should contain a type supported by one of the registered NSImageRep subclasses. Table 1 lists the default pasteboard types and file extensions for several NSImageRep subclasses.

Table 1  Default pasteboard types for image representations

Image representation class

Default pasteboard type

Default file extensions

NSBitmapImageRep

NSTIFFPboardType

tiff, gif, jpg, and others

NSPDFImageRep

NSPDFPboardType

pdf

NSEPSImageRep

NSPostscriptPboardType

eps

NSPICTImageRep

NSPICTPboardType

pict

If the specified pasteboard contains the value NSFilenamesPboardType, each filename on the pasteboard should have an extension supported by one of the registered NSImageRep subclasses. You can use the imageUnfilteredFileTypes method of a given subclass to obtain the list of supported types for that class.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

initWithSize:

Initializes and returns an image object with the specified dimensions.

- (id)initWithSize:(NSSize)aSize
Parameters
aSize

The size of the image, measured in points.

Return Value

An initialized NSImage object with no rendered content.

Discussion

This method does not add any image representations to the image object. It is permissible to initialize the image object by passing a size of (0.0, 0.0); however, you must set the size to a non-zero value before using it or an exception will be raised.

After using this method to initialize an image object, you are expected to provide the image contents before trying to draw the image. You might lock focus on the image and draw to the image or you might explicitly add an image representation that you created.

Availability
  • Available in OS X v10.0 and later.
See Also
Declared In
NSImage.h

isTemplate

Returns a Boolean value indicating whether the image is a template image.

- (BOOL)isTemplate
Return Value

YES if the image is a template image; otherwise, NO.

Discussion

Template images consist of black and clear colors (and an alpha channel). Template images are not intended to be used as standalone images and are usually mixed with other content to create the desired final appearance.

Availability
  • Available in OS X v10.5 and later.
Declared In
NSImage.h

isValid

Returns a Boolean value indicating whether an image representation from the receiver can be drawn.

- (BOOL)isValid
Return Value

YES if the receiver can be drawn; otherwise, NO.

Discussion

If the receiver is initialized with an existing image file, but the corresponding image data is not yet loaded into memory, this method loads the data and expands it as needed. If the receiver contains no image representations and no associated image file, this method creates a valid cached image representation and initializes it to the default bit depth. This method returns NO in cases where the file or URL from which it was initialized is nonexistent or when the data in an existing file is invalid.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

layerContentsForContentsScale:

Returns an object that may be used as the contents of a layer.

- (id)layerContentsForContentsScale:(CGFloat)layerContentsScale
Parameters
layerContentsScale

The scale factor for the resulting image. Obtain the value for this parameter by calling the recommendedLayerContentsScale: method.

Return Value

A object that you can assign to the contents property of a CALayer object. This object contains the image data from the current image optimized for the specified scale factor.

Discussion

Use this method in situations where you want to use the image as the contents of a layer. This method provides the image data wrapped in an object that correctly respects all of the possible content gravities supported by the layer. Use of the returned object as the layer’s contents is recommended over the use of the NSImage object itself.

Availability
  • Available in OS X v10.7 and later.
Declared In
NSImage.h

lockFocus

Prepares the image to receive drawing commands.

- (void)lockFocus
Discussion

This method sets the current drawing context to the area of the offscreen window used to cache the receiver's contents. Subsequent drawing commands are composited to this offscreen window. If the offscreen drawing area already has some content, any new drawing commands are composited with that content. This method does not modify the original image data directly.

When locking focus, this method chooses the best image representation object available and locks focus on that object. If the receiver has no image representations, this method creates one with the default depth and locks focus on it. For information on how the "best" representation is chosen, see the “Images” chapter of Cocoa Drawing Guide.

A successful lockFocus message must be balanced with a matching unlockFocus message to the same NSImage object. These messages bracket the code that draws the image.

If lockFocus is unable to focus on the image, it raises an NSImageCacheException.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

lockFocusFlipped:

Prepares the image to receive drawing commands using the specified flipped state.

- (void)lockFocusFlipped:(BOOL)flipped
Parameters
flipped

YES if the drawing context should be flipped, otherwise NO.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSImage.h

matchesOnlyOnBestFittingAxis

Returns whether the image matches only on the best fitting axis.

- (BOOL)matchesOnlyOnBestFittingAxis
Return Value

YES if the image is drawn only on the best fitting axis; otherwise NO;

Discussion

NSImage has always tried to use a representation with at least as many pixels as the destination rectangle. Many apps try to implement banners and 3 part / 9 part images by stretching an NSImage over a much larger area (usually only on a single axis).

With the addition of 2x assets these apps are finding this policy displays the 2x image rep when they would prefer the 1x rep. This behavior can be changed by using this method.

Availability
  • Available in OS X v10.7 and later.
Declared In
NSImage.h

matchesOnMultipleResolution

Returns a Boolean value indicating whether image representations whose resolution is an integral multiple of the device resolution are considered a match.

- (BOOL)matchesOnMultipleResolution
Return Value

YES if image representations whose resolution is an integral multiple of the device resolution are considered a match; otherwise, NO.

Discussion

When this method returns NO, only image representations whose resolution is exactly the same as the device resolution are considered matches. If this method returns YES and multiple image representations fit this criteria, the one whose resolution is closest to the device resolution is chosen.

The default value is YES.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

name

Returns the name associated with the receiver, if any.

- (NSString *)name
Return Value

The name associated with the receiver, or nil if no name is assigned.

Availability
  • Available in OS X v10.0 and later.
See Also
Related Sample Code
Declared In
NSImage.h

prefersColorMatch

Returns a Boolean value indicating whether the image prefers to choose image representations using color matching or resolution matching.

- (BOOL)prefersColorMatch
Return Value

YES if color matching is preferred over resolution matching; otherwise NO if resolution matching is preferred.

Discussion

Both color matching and resolution matching may influence the choice of an image representation. This method simply indicates which technique is used first during the selection process. The default value is YES.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

recache

Invalidates and frees the offscreen caches of all image representations.

- (void)recache
Discussion

If you modify an image representation, you must send a recache message to the corresponding image object to force the changes to be recached. The next time any image representation is drawn, it is asked to recreate its cached image. If you do not send this message, the image representation may use the old cache data. This method simply clears the cached image data; it does not delete the NSCachedImageRep objects associated with any image representations.

If you do not plan to use an image again right away, you can free its caches to reduce the amount of memory consumed by your program.

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSImage.h

recommendedLayerContentsScale:

Returns the recommended layer contents scale for this image.

- (CGFloat)recommendedLayerContentsScale:(CGFloat)preferredContentsScale
Parameters
preferredContentsScale

The preferred layer contents scale. Don't use a higher scale factor if the image can't provide it. If the image is resolution independent the return value will be the same as the input. If you specify 0.0 for this parameter, the method uses the scale factor for the default screen.

Return Value

The recommended layer contents scale. This scale factor may be different than the one in the preferredContentsScale parameter.

Discussion

Use this method to obtain the scale factor value that you pass to the layerContentsForContentsScale: method. This method uses the image data to determine the scale factor that is best suited for creating an image that looks good in the layer.

Availability
  • Available in OS X v10.7 and later.
Declared In
NSImage.h

removeRepresentation:

Removes the specified image representation from the receiver and releases it.

- (void)removeRepresentation:(NSImageRep *)imageRep
Parameters
imageRep

The image representation object you want to remove.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

representations

Returns an array containing all of the receiver's image representations.

- (NSArray *)representations
Return Value

An array containing zero or more NSImageRep objects.

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSImage.h

setAccessibilityDescription:

Sets the image’s accessibility description.

- (void)setAccessibilityDescription:(NSString *)description
Parameters
description

A short localized string that does not include the name of the interface element.

Discussion

This description will be used automatically by interface elements that display images. Like all accessibility descriptions, the string should be a short localized string that does not include the name of the interface element. For instance, "delete" rather than "delete button".

Availability
  • Available in OS X v10.6 and later.
Related Sample Code
Declared In
NSImage.h

setAlignmentRect:

Sets the alignment metadata that your code can use to position the image during layout.

- (void)setAlignmentRect:(NSRect)rect
Parameters
rect

The alignment rectangle for the image.

Discussion

Alignment rectangles specify baselines that you can use to position the content of an image more accurately. These baselines are merely hints that your own code can use to determine positioning and are not used internally by NSImage itself during drawing. For example, if you have a 20 x 20 pixel icon that includes a glow effect, you might set the alignment rectangle to {{2, 2}, {16, 16}} to indicate the position of the underlying icon without the glow effect.

Availability
  • Available in OS X v10.5 and later.
Declared In
NSImage.h

setBackgroundColor:

Sets the background color of the image.

- (void)setBackgroundColor:(NSColor *)aColor
Parameters
aColor

The new background color for the image.

Discussion

The background color is visible only if the drawn image representation does not completely cover all of the pixels available for the image's current size. The background color is ignored for cached image representations; such caches are always created with a white background. This method does not cause the receiver to recache itself.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

setCacheMode:

Set the receiver’s caching mode.

- (void)setCacheMode:(NSImageCacheMode)mode
Parameters
mode

The caching mode to use with this image. For a list of possible values, see NSImageCacheMode.

Discussion

The caching mode determines when the receiver's image representations use offscreen caches. Offscreen caches speed up rendering time but do so by using extra memory. In the default caching mode (NSImageCacheDefault), each image representation chooses the caching technique that produces the fastest drawing times. For example, in the default mode, the NSPDFImageRep and NSEPSImageRep classes use the NSImageCacheAlways mode but the NSBitmapImageRep class uses the NSImageCacheBySize mode.

For more information on image caching behavior, see the “Images” chapter of Cocoa Drawing Guide.

Availability
  • Available in OS X v10.2 and later.
Declared In
NSImage.h

setDelegate:

Sets the delegate object of the receiver.

- (void)setDelegate:(id < NSImageDelegate >)anObject
Parameters
anObject

The new delegate object.

Availability
  • Available in OS X v10.0 and later.
See Also
Declared In
NSImage.h

setMatchesOnlyOnBestFittingAxis:

Set whether the image only resizes on the best fitting axis.

- (void)setMatchesOnlyOnBestFittingAxis:(BOOL)flag
Parameters
flag

YES if the image should match only on the best fitting axis; otherwise NO.

Discussion

NSImage has always tried to use a representation with at least as many pixels as the destination rectangle. Many apps try to implement banners and 3 part / 9 part images by stretching an NSImage over a much larger area (usually only on a single axis).

With the addition of 2x assets these apps are finding this policy displays the 2x image rep when they would prefer the 1x rep. This behavior can be changed by using this method.

Availability
  • Available in OS X v10.7 and later.
Declared In
NSImage.h

setMatchesOnMultipleResolution:

Sets whether image representations whose resolutions are integral multiples of the device resolution are considered a match.

- (void)setMatchesOnMultipleResolution:(BOOL)flag
Parameters
flag

YES if image representations whose resolution is an integral multiple of the device resolution should be considered a match; otherwise, NO.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

setName:

Registers the receiver under the specified name.

- (BOOL)setName:(NSString *)aString
Parameters
aString

The name to associate with the receiver. Specify nil if you want to remove the image from the image cache.

Return Value

YES if the receiver was successfully registered with the given name; otherwise, NO.

Discussion

If the receiver is already registered under a different name, this method unregisters the other name. If a different image is already registered under the name specified in aString, this method does nothing and returns NO.

When naming an image using this method, it is convention not to include filename extensions in the names you specify. That way, you can easily distinguish between images you have named explicitly and those you want to load from the app's bundle. For information about the rules used to search for images, and for information about the ownership policy of named images, see the imageNamed: method.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

setPrefersColorMatch:

Sets whether choosing an image representation favors color matching over resolution matching.

- (void)setPrefersColorMatch:(BOOL)flag
Parameters
flag

YES if the receiver should match the color capabilities of the rendering device first; otherwise, NO to indicate that resolution matching is preferred.

Discussion

Both color matching and resolution matching may influence the choice of an image representation. You use this method to choose which technique should be used first during the selection process.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

setSize:

Sets the width and height of the image.

- (void)setSize:(NSSize)aSize
Parameters
aSize

The new size of the image, measured in points.

Discussion

The size of an NSImage object must be set before it can be used. If the size of the image hasn’t already been set when an image representation is added, the size is taken from the image representation's data. For EPS images, the size is taken from the image's bounding box. For TIFF images, the size is taken from the ImageLength and ImageWidth attributes.

Changing the size of an NSImage after it has been used effectively resizes the image. Changing the size invalidates all its caches and frees them. When the image is next composited, the selected representation will draw itself in an offscreen window to recreate the cache.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

setTemplate:

Sets whether the image represents a template image.

- (void)setTemplate:(BOOL)isTemplate
Parameters
isTemplate

Specify YES if the image is a template image; otherwise, NO.

Discussion

Images you mark as template images should consist of only black and clear colors. You can use the alpha channel in the image to adjust the opacity of black content, however.

Template images are not intended to be used as standalone images. They are always mixed with other content and processed to create the desired appearance. You can mark an image as a “template image” to notify clients who care that the image contains only black and clear content. The most common use for template images is in image cells. For example, you might use a template image to provide the content for a button or segmented control. Cocoa cells take advantage of the nature of template images—that is, their simplified color scheme and use of transparency—to improve the appearance of the corresponding control in each of its supported states.

Availability
  • Available in OS X v10.5 and later.
Declared In
NSImage.h

setUsesEPSOnResolutionMismatch:

Sets whether EPS image representations are preferred when no other representations match the resolution of the device.

- (void)setUsesEPSOnResolutionMismatch:(BOOL)flag
Parameters
flag

YES if EPS image representations are preferred; otherwise NO.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

size

Returns the size of the receiver.

- (NSSize)size
Return Value

The size of the receiver or (0.0, 0.0) if no size has been set and the size cannot be determined from any of the receiver's image representations.

Availability
  • Available in OS X v10.0 and later.
See Also
Declared In
NSImage.h

TIFFRepresentation

Returns a data object containing TIFF data for all of the image representations in the receiver.

- (NSData *)TIFFRepresentation
Return Value

A data object containing the TIFF data, or nil if the TIFF data could not be created.

Discussion

You can use the returned data object to write the TIFF data to a file. For each image representation, this method uses the TIFF compression option associated with that representation or NSTIFFCompressionNone, if no option is set.

If one of the receiver's image representations does not support the creation of TIFF data natively (PDF and EPS images, for example), this method creates the TIFF data from that representation's cached content.

Additional image formats can be saved by using the NSBitmapImageRep method representationUsingType:properties:.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

TIFFRepresentationUsingCompression:factor:

Returns a data object containing TIFF data with the specified compression settings for all of the image representations in the receiver.

- (NSData *)TIFFRepresentationUsingCompression:(NSTIFFCompression)comp factor:(float)aFloat
Parameters
comp

The type of compression to use. For a list of values, see the constants in NSBitmapImageRep.

aFloat

Provides a hint for compression types that implement variable compression ratios. Currently, only JPEG compression uses a compression factor.

Return Value

A data object containing the TIFF data, or nil if the TIFF data could not be created.

Discussion

You can use the returned data object to write the TIFF data to a file. If the specified compression isn’t applicable, no compression is used. If a problem is encountered during generation of the TIFF data, this method may raise an exception.

If one of the receiver's image representations does not support the creation of TIFF data natively (PDF and EPS images, for example), this method creates the TIFF data from that representation's cached content.

Additional image formats can be saved by using the NSBitmapImageRep method representationUsingType:properties:.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

unlockFocus

Removes the focus from the receiver.

- (void)unlockFocus
Discussion

This message must be sent after a successful lockFocus or lockFocusOnRepresentation: message and the completion of any intermediate drawing commands. This method restores the focus to the previous owner, if any.

Do not send this message if the preceding call to lock focus raised an NSImageCacheException.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

usesEPSOnResolutionMismatch

Returns a Boolean value indicating whether EPS representations are preferred when no other representations match the resolution of the device.

- (BOOL)usesEPSOnResolutionMismatch
Return Value

YES if EPS image representations are preferred; otherwise NO.

Discussion

The default value is NO.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSImage.h

Constants

Image Hint Dictionary Keys

These constants are a subset of the dictionary keys used in the hints dictionary for the methods CGImageForProposedRect:context:hints:, bestRepresentationForRect:context:hints:, drawInRect:fromRect:operation:fraction:respectFlipped:hints:, and hitTestRect:withImageDestinationRect:context:hints:flipped:. Additional hint keys are also valid including: Context Options in CIContext, and the entries in an NSScreen device description dictionary as described in deviceDescription.

NSString *const NSImageHintCTM;
NSString *const NSImageHintInterpolation;
Constants
NSImageHintCTM

Provides a context transform hint. The value for this key is an NSAffineTransform.

Available in OS X v10.6 and later.

Declared in NSImage.h.

NSImageHintInterpolation

Provides an interpolation hint. The value for this key is an NSNumber with an NSImageInterpolation value.

Available in OS X v10.6 and later.

Declared in NSImage.h.

NSCompositingOperation

These constants specify compositing operators described in terms of having source and destination images, each having an opaque and transparent region. The destination image after the operation is defined in terms of the source and destination before images.

enum {
   NSCompositeClear           = 0,
   NSCompositeCopy            = 1,
   NSCompositeSourceOver      = 2,
   NSCompositeSourceIn        = 3,
   NSCompositeSourceOut       = 4,
   NSCompositeSourceAtop      = 5,
   NSCompositeDestinationOver = 6,
   NSCompositeDestinationIn   = 7,
   NSCompositeDestinationOut  = 8,
   NSCompositeDestinationAtop = 9,
   NSCompositeXOR             = 10,
   NSCompositePlusDarker      = 11,
   NSCompositeHighlight       = 12,
   NSCompositePlusLighter     = 13
}
typedef NSUInteger NSCompositingOperation;
Constants
NSCompositeClear

Transparent. (R = 0)

Available in OS X v10.0 and later.

Declared in NSGraphics.h.

NSCompositeCopy

Source image. (R = S)

Available in OS X v10.0 and later.

Declared in NSGraphics.h.

NSCompositeSourceOver

Source image wherever source image is opaque, and destination image elsewhere. (R = S + D*(1 - Sa))

Available in OS X v10.0 and later.

Declared in NSGraphics.h.

NSCompositeSourceIn

Source image wherever both images are opaque, and transparent elsewhere. (R = S*Da)

Available in OS X v10.0 and later.

Declared in NSGraphics.h.

NSCompositeSourceOut

Source image wherever source image is opaque but destination image is transparent, and transparent elsewhere. (R = S*(1 - Da))

Available in OS X v10.0 and later.

Declared in NSGraphics.h.

NSCompositeSourceAtop

Source image wherever both images are opaque, destination image wherever destination image is opaque but source image is transparent, and transparent elsewhere. (R = S*Da + D*(1 - Sa))

Available in OS X v10.0 and later.

Declared in NSGraphics.h.

NSCompositeDestinationOver

Destination image wherever destination image is opaque, and source image elsewhere. (R = S*(1 - Da) + D)

Available in OS X v10.0 and later.

Declared in NSGraphics.h.

NSCompositeDestinationIn

Destination image wherever both images are opaque, and transparent elsewhere. (R = D*Sa)

Available in OS X v10.0 and later.

Declared in NSGraphics.h.

NSCompositeDestinationOut

Destination image wherever destination image is opaque but source image is transparent, and transparent elsewhere. (R = D*(1 - Sa))

Available in OS X v10.0 and later.

Declared in NSGraphics.h.

NSCompositeDestinationAtop

Destination image wherever both images are opaque, source image wherever source image is opaque but destination image is transparent, and transparent elsewhere. (R = S*(1 - Da) + D*Sa)

Available in OS X v10.0 and later.

Declared in NSGraphics.h.

NSCompositeXOR

Exclusive OR of source and destination images. (R = S*(1 - Da) + D*(1 - Sa))

Works only with black and white images and is not recommended for color contexts.

Available in OS X v10.0 and later.

Declared in NSGraphics.h.

NSCompositePlusDarker

Sum of source and destination images, with color values approaching 0 as a limit. (R = MAX(0, (1 - D) + (1 - S)))

Available in OS X v10.0 and later.

Declared in NSGraphics.h.

NSCompositeHighlight

Source image wherever source image is opaque, and destination image elsewhere. (Deprecated. Mapped to NSCompositeSourceOver.)

Available in OS X v10.0 and later.

Declared in NSGraphics.h.

NSCompositePlusLighter

Sum of source and destination images, with color values approaching 1 as a limit. (R = MIN(1, S + D))

Available in OS X v10.0 and later.

Declared in NSGraphics.h.

Discussion

These compositing operators are defined in and used by compositeToPoint:fromRect:operation:, compositeToPoint:operation:, compositeToPoint:fromRect:operation:fraction:, compositeToPoint:operation:fraction:, drawAtPoint:fromRect:operation:fraction:, and drawInRect:fromRect:operation:fraction:. They are also used by drawing methods in other classes that take a compositing operator.

The equations after each constant represent the mathematical formulas used to calculate the color value of the resulting pixel. Table 2 lists the meaning of each placeholder value in the equations.

Table 2  Placeholder values for compositing equations

Para

Para

R

The premultiplied result color.

S

The source color

D

The destination color

Sa

The alpha value of the source color

Da

The alpha value of the destination color

Availability
  • Available in OS X v10.0 and later.
Declared In
NSGraphics.h

NSImageLoadStatus

These constants are status values passed to the incremental loading delegate method image:didLoadRepresentation:withStatus:.

enum {
   NSImageLoadStatusCompleted,
   NSImageLoadStatusCancelled,
   NSImageLoadStatusInvalidData,
   NSImageLoadStatusUnexpectedEOF,
   NSImageLoadStatusReadError
}
typedef NSUInteger NSImageLoadStatus;
Constants
NSImageLoadStatusCompleted

Enough data has been provided to completely decompress the image.

Available in OS X v10.2 and later.

Declared in NSImage.h.

NSImageLoadStatusCancelled

Image loading was canceled.

The image contains the portions of the data that have already been successfully decompressed, if any.

Available in OS X v10.2 and later.

Declared in NSImage.h.

NSImageLoadStatusInvalidData

An error occurred during image decompression.

The image data is probably corrupt. The image contains the portions of the data that have already been successfully decompressed, if any.

Available in OS X v10.2 and later.

Declared in NSImage.h.

NSImageLoadStatusUnexpectedEOF

Not enough data was available for full decompression of the image.

The image contains the portions of the data that have already been successfully decompressed, if any.

Available in OS X v10.2 and later.

Declared in NSImage.h.

NSImageLoadStatusReadError

Not enough data was available for full decompression of the image.

The image contains the portions of the data that have already been successfully decompressed, if any.

Available in OS X v10.2 and later.

Declared in NSImage.h.

Availability
  • Available in Mac OS X v10.2 and later.
Declared In
NSImage.h

NSImageCacheMode

These constants specify the caching policy on a per NSImage basis. The caching policy is set using cacheMode and setCacheMode:.

enum {
   NSImageCacheDefault,
   NSImageCacheAlways,
   NSImageCacheBySize,
   NSImageCacheNever
}
typedef NSUInteger NSImageCacheMode;
Constants
NSImageCacheDefault

Caching is unspecified.

Use the image rep's default.

Available in OS X v10.2 and later.

Declared in NSImage.h.

NSImageCacheAlways

Always generate a cache when drawing.

Available in OS X v10.2 and later.

Declared in NSImage.h.

NSImageCacheBySize

Cache if cache size is smaller than the original data.

Available in OS X v10.2 and later.

Declared in NSImage.h.

NSImageCacheNever

Never cache; always draw direct.

Available in OS X v10.2 and later.

Declared in NSImage.h.

Discussion

The following table specifies the default caching policy for the various types of image representation.

Image Rep Class

Default caching policy

NSBitmapImageRep

NSImageCacheBySize. Cache if bitmap is 32-bits in 16-bit world or greater than 72 dpi.

NSPICTImageRep

NSImageCacheBySize. Same reasoning as NSBitmapImageRep in the event the PICT contains a bitmap.

NSPDFImageRep

NSImageCacheAlways

NSCIImageRep

NSImageCacheBySize. Cache if the bitmap depth does not match the screen depth or the resolution is greater than 72 dpi.

NSEPSImageRep

NSImageCacheAlways

NSCustomImageRep

NSImageCacheAlways

Availability
  • Available in Mac OS X v10.2 and later.
Declared In
NSImage.h

Image Template Constants

Images representing standard artwork and icons that you can use in your apps

NSString *const NSImageNameQuickLookTemplate;
NSString *const NSImageNameBluetoothTemplate;
NSString *const NSImageNameIChatTheaterTemplate;
NSString *const NSImageNameSlideshowTemplate;
NSString *const NSImageNameActionTemplate;
NSString *const NSImageNameSmartBadgeTemplate;
NSString *const NSImageNamePathTemplate;
NSString *const NSImageNameInvalidDataFreestandingTemplate;
NSString *const NSImageNameLockLockedTemplate;
NSString *const NSImageNameLockUnlockedTemplate;
NSString *const NSImageNameGoRightTemplate;
NSString *const NSImageNameGoLeftTemplate;
NSString *const NSImageNameRightFacingTriangleTemplate;
NSString *const NSImageNameLeftFacingTriangleTemplate;
NSString *const NSImageNameAddTemplate;
NSString *const NSImageNameRemoveTemplate;
NSString *const NSImageNameRevealFreestandingTemplate;
NSString *const NSImageNameFollowLinkFreestandingTemplate;
NSString *const NSImageNameEnterFullScreenTemplate;
NSString *const NSImageNameExitFullScreenTemplate;
NSString *const NSImageNameStopProgressTemplate;
NSString *const NSImageNameStopProgressFreestandingTemplate;
NSString *const NSImageNameRefreshTemplate;
NSString *const NSImageNameRefreshFreestandingTemplate;
Constants
NSImageNameQuickLookTemplate

A Quick Look template image. NSImageNameQuickLookTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameBluetoothTemplate

A Bluetooth template image. NSImageNameBluetoothTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameIChatTheaterTemplate

An iChat Theater template image. NSImageNameIChatTheaterTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameSlideshowTemplate

A slideshow template image. NSImageNameSlideshowTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameActionTemplate

An action menu template image. NSImageNameActionTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameSmartBadgeTemplate

A badge for a “smart” item. NSImageNameSmartBadgeTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNamePathTemplate

A path button template image. NSImageNamePathTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameInvalidDataFreestandingTemplate

An invalid data template image. Place this icon to the right of any fields containing invalid data. You can use this image to implement a borderless button. NSImageNameInvalidDataFreestandingTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameLockLockedTemplate

A locked lock template image. Use to indicate locked content. NSImageNameLockLockedTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameLockUnlockedTemplate

An unlocked lock template image. Use to indicate modifiable content that can be locked. NSImageNameLockUnlockedTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameGoRightTemplate

A “go forward” template image. NSImageNameGoRightTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameGoLeftTemplate

A “go back” template image. NSImageNameGoLeftTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameRightFacingTriangleTemplate

A generic right-facing triangle template image. NSImageNameRightFacingTriangleTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameLeftFacingTriangleTemplate

A generic left-facing triangle template image. NSImageNameLeftFacingTriangleTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameAddTemplate

An add item template image. NSImageNameAddTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameRemoveTemplate

A remove item template image. NSImageNameRemoveTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameRevealFreestandingTemplate

A reveal contents template image. You can use this image to implement a borderless button. NSImageNameRevealFreestandingTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameFollowLinkFreestandingTemplate

A link template image. You can use this image to implement a borderless button. NSImageNameFollowLinkFreestandingTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameEnterFullScreenTemplate

An enter full-screen mode template image. NSImageNameEnterFullScreenTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameExitFullScreenTemplate

An exit full-screen mode template image. NSImageNameExitFullScreenTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameStopProgressTemplate

A stop progress button template image. NSImageNameStopProgressTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameStopProgressFreestandingTemplate

A stop progress template image. You can use this image to implement a borderless button. NSImageNameStopProgressFreestandingTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameRefreshTemplate

A refresh template image. NSImageNameRefreshTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameRefreshFreestandingTemplate

A refresh template image. You can use this image to implement a borderless button. NSImageNameRefreshFreestandingTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

Discussion

To access these images, pass the specified constant to the imageNamed: method.

Images with the word “Template” in their title identify shapes that are not intended as standalone images. You would typically use these icons as the custom image for a button, or you might apply them to a cell in a control. For example, you might use the NSImageNameLockLockedTemplate image to indicate an item is not modifiable. Template images should use black and clear colors only and it is fine to include varying levels of alpha.

Images with the word “Freestanding” in their title can be used to implement borderless buttons. You do not need to include any extra bezel artwork behind such images.

You should always use named images according to their intended purpose, and not according to how the image appears when loaded. The appearance of images can change between releases. If you use an image for its intended purpose (and not because of it looks), your code should look correct from release to release.

The size and aspect ratio of system images may change from release to release. In some situations, you should explicitly resize images as appropriate for your use. If you use these images in conjunction with an NSButtonCell object, however, you can use the setImageScaling: method of the cell to control scaling instead. Similarly, for an NSSegmentedCell object, you can use the setImageScaling:forSegment: method to control scaling.

The string value for each constant is equal to the constant name without the “ImageName” portion. You might need this information to locate images by name in Interface Builder. For example, the constant NSImageNameRefreshFreestandingTemplate would correspond to an image named “NSRefreshFreestandingTemplate” in Interface Builder.

Declared In
NSImage.h

Multiple Documents Drag Image

Drag images you can use in your apps. To access this image, pass the specified constant to the imageNamed: method.

NSString *const NSImageNameMultipleDocuments;
Constants
NSImageNameMultipleDocuments

A drag image for multiple items. NSImageNameMultipleDocuments

Available in OS X v10.5 and later.

Declared in NSImage.h.

Discussion

You can use this icon as the drag image when dragging multiple items. You should not use this image for any other intended purpose, however. The appearance of images can change between releases. If you use an image for its intended purpose (and not because of how it looks), your code should look correct from release to release.

The size and aspect ratio of system images may change from release to release. In some situations, you should explicitly resize images as appropriate for your use. If you use these images in conjunction with an NSButtonCell object, however, you can use the setImageScaling: method of the cell to control scaling instead. Similarly, for an NSSegmentedCell object, you can use the setImageScaling:forSegment: method to control scaling.

The string value for each constant is equal to the constant name without the “ImageName” portion. You might need this information to locate images by name in Interface Builder. For example, the constant NSImageNameMultipleDocuments would correspond to an image named “NSMultipleDocuments” in Interface Builder.

Sharing Permissions Named Images

Images representing sharing permission icons that you can use in your apps. To access this image, pass the specified constant to the imageNamed: method.

NSString *const NSImageNameUser;
NSString *const NSImageNameUserGroup;
NSString *const NSImageNameEveryone;
NSString *const NSImageNameUserGuest;
Constants
NSImageNameUser

Permissions for a single user. NSImageNameUser

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameUserGroup

Permissions for a group of users. NSImageNameUserGroup

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameEveryone

Permissions for all users. NSImageNameEveryone

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameUserGuest

Permissions for guests.../art/NSUserGuest_2x.png

Available in OS X v10.6 and later.

Declared in NSImage.h.

Discussion

You should use these images to reflect user and group permission or sharing information. The appearance of images can change between releases. If you use an image for its intended purpose (and not because of how it looks), your code should look correct from release to release.

The size and aspect ratio of system images may change from release to release. In some situations, you should explicitly resize images as appropriate for your use. If you use these images in conjunction with an NSButtonCell object, however, you can use the setImageScaling: method of the cell to control scaling instead. Similarly, for an NSSegmentedCell object, you can use the setImageScaling:forSegment: method to control scaling.

The string value for each constant is equal to the constant name without the “ImageName” portion. You might need this information to locate images by name in Interface Builder. For example, the constant NSImageNameEveryone would correspond to an image named “NSEveryone” in Interface Builder.

System Entity Images

Images representing Finder items. To access this image, pass the specified constant to the imageNamed: method.

NSString *const NSImageNameBonjour;
NSString *const NSImageNameDotMac;
NSString *const NSImageNameComputer;
NSString *const NSImageNameFolderBurnable;
NSString *const NSImageNameFolderSmart;
NSString *const NSImageNameNetwork;
Constants
NSImageNameBonjour

A Bonjour icon. NSImageNameBonjour

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameDotMac

A Dot Mac icon. NSImageNameDotMac

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameComputer

A computer icon. NSImageNameComputer

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameFolderBurnable

A burnable folder icon. NSImageNameFolderBurnable

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameFolderSmart

A smart folder icon. NSImageNameFolderSmart

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameNetwork

A network icon. NSImageNameNetwork

Available in OS X v10.5 and later.

Declared in NSImage.h.

Discussion

You should use these images to reflect specific elements of the Mac OS X environment. For example, you might use the burnable folder icon if your software allows the user to organize content for burning onto an optical disk. The appearance of images can change between releases. If you use an image for its intended purpose (and not because of how it looks), your code should look correct from release to release.

The size and aspect ratio of system images may change from release to release. In some situations, you should explicitly resize images as appropriate for your use. If you use these images in conjunction with an NSButtonCell object, however, you can use the setImageScaling: method of the cell to control scaling instead. Similarly, for an NSSegmentedCell object, you can use the setImageScaling:forSegment: method to control scaling.

The string value for each constant is equal to the constant name without the “ImageName” portion. You might need this information to locate images by name in Interface Builder. For example, the constant NSImageNameNetwork would correspond to an image named “NSNetwork” in Interface Builder.

Declared In
NSImage.h

Toolbar Named Images

Images that you can use in app toolbars. To access this image, pass the specified constant to the imageNamed: method.

NSString *const NSImageNameUserAccounts;
NSString *const NSImageNamePreferencesGeneral;
NSString *const NSImageNameAdvanced;
NSString *const NSImageNameInfo;
NSString *const NSImageNameFontPanel;
NSString *const NSImageNameColorPanel;
NSString *const NSImageNameFolder;
NSString *const NSImageNameTrashEmpty;
NSString *const NSImageNameTrashFull;
NSString *const NSImageNameHomeTemplate;
NSString *const NSImageNameBookmarksTemplate;
NSString *const NSImageNameCaution;
NSString *const NSImageNameStatusAvailable;
NSString *const NSImageNameStatusPartiallyAvailable;
NSString *const NSImageNameStatusUnavailable;
NSString *const NSImageNameStatusNone;
NSString *const NSImageNameApplicationIcon;
NSString *const NSImageNameMenuOnStateTemplate;
NSString *const NSImageNameMenuMixedStateTemplate;
NSString *const NSImageNameMobileMe;
Constants
NSImageNameUserAccounts

User account toolbar icon. Use in a preferences window only. NSImageNameUserAccounts

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNamePreferencesGeneral

General preferences toolbar icon. Use in a preferences window only. NSImageNamePreferencesGeneral

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameAdvanced

Advanced preferences toolbar icon. Use in a preferences window only. NSImageNameAdvanced

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameInfo

An information toolbar icon. NSImageNameInfo

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameFontPanel

A font panel toolbar icon. NSImageNameFontPanel

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameColorPanel

A color panel toolbar icon. NSImageNameColorPanel

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameFolder

A folder image. ../art/NSFolder_2x.png

Available in OS X v10.6 and later.

Declared in NSImage.h.

NSImageNameTrashEmpty

An image of the empty trash can.../art/NSTrashEmpty_2x.png

Available in OS X v10.6 and later.

Declared in NSImage.h.

NSImageNameTrashFull

An image of the full trash can.../art/NSTrashFull_2x.png

Available in OS X v10.6 and later.

Declared in NSImage.h.

NSImageNameHomeTemplate

Home image suitable for a template.../art/NSHomeTemplate_2x.png

Available in OS X v10.6 and later.

Declared in NSImage.h.

NSImageNameBookmarksTemplate

Bookmarks image suitable for a template.../art/NSBookmarksTemplate_2x.png

Available in OS X v10.6 and later.

Declared in NSImage.h.

NSImageNameCaution

Caution Image.../art/NSCaution_2x.png

Available in OS X v10.6 and later.

Declared in NSImage.h.

NSImageNameStatusAvailable

Small green indicator, similar to iChat’s available image. ../art/NSStatusAvailable_2x.png

Available in OS X v10.6 and later.

Declared in NSImage.h.

NSImageNameStatusPartiallyAvailable

Small yellow indicator, similar to iChat’s idle image.../art/NSStatusPartiallyAvailable_2x.png

Available in OS X v10.6 and later.

Declared in NSImage.h.

NSImageNameStatusUnavailable

Small red indicator, similar to iChat’s unavailable image.../art/NSStatusUnavailable_2x.png

Available in OS X v10.6 and later.

Declared in NSImage.h.

NSImageNameStatusNone

Small clear indicator.../art/NSStatusNone_2x.png

Available in OS X v10.6 and later.

Declared in NSImage.h.

NSImageNameApplicationIcon

The app’s icon.

On versions of Mac OS X prior to v10.6, you can use the string @"NSApplicationIcon".

Available in OS X v10.6 and later.

Declared in NSImage.h.

NSImageNameMenuOnStateTemplate

A check mark. Drawing these outside of menus is discouraged.../art/NSMenuOnStateTemplate_2x.png

Available in OS X v10.6 and later.

Declared in NSImage.h.

NSImageNameMenuMixedStateTemplate

A horizontal dash. Drawing these outside of menus is discouraged. ../art/NSMenuMixedStateTemplate_2x.png

Available in OS X v10.6 and later.

Declared in NSImage.h.

NSImageNameMobileMe

MobileMe logo. Note that this is preferred to using the NSImageNameDotMac image, although that image is not expected to be deprecated. ../art/NSMobileMe_2x.png

Available in OS X v10.6 and later.

Declared in NSImage.h.

Discussion

You should use these images as icons for toolbar items. The appearance of images can change between releases. If you use an image for its intended purpose (and not because of how it looks), your code should look correct from release to release.

The size and aspect ratio of system images may change from release to release. In some situations, you should explicitly resize images as appropriate for your use. If you use these images in conjunction with an NSButtonCell object, however, you can use the setImageScaling: method of the cell to control scaling instead. Similarly, for an NSSegmentedCell object, you can use the setImageScaling:forSegment: method to control scaling.

Constants that end in the word "Template" name black and clear images that return YES for isTemplate. These images can be processed into variants appropriate for different situations. For example, these images can invert in a selected table view row. See setTemplate:: for more comments. These images are inappropriate for display without further processing, but NSCell and its subclasses will perform the processing.

Some images also contain the word "Freestanding". This indicates that an image is appropriate for use as a borderless button, it doesn't need any extra bezel artwork behind it.

The string value for each constant is equal to the constant name without the “ImageName” portion. You might need this information to locate images by name in Interface Builder. For example, the constant NSImageNameColorPanel would correspond to an image named “NSColorPanel” in Interface Builder.

Declared In
NSImage.h

View Type Template Images

Images used in segmented controls to switch the current view type. To access this image, pass the specified constant to the imageNamed: method.

NSString *const NSImageNameIconViewTemplate;
NSString *const NSImageNameListViewTemplate;
NSString *const NSImageNameColumnViewTemplate;
NSString *const NSImageNameFlowViewTemplate;
NSString *const NSImageNameShareTemplate;
Constants
NSImageNameIconViewTemplate

An icon view mode template image. NSImageNameIconViewTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameListViewTemplate

A list view mode template image. NSImageNameListViewTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameColumnViewTemplate

A column view mode template image. NSImageNameColumnViewTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameFlowViewTemplate

A cover flow view mode template image. NSImageNameFlowViewTemplate

Available in OS X v10.5 and later.

Declared in NSImage.h.

NSImageNameShareTemplate

A share view template image. ../art/NSShareTemplate_2x.png

Available in OS X v10.8 and later.

Declared in NSImage.h.

Discussion

Images with the word “Template” in their title identify shapes that are not intended as standalone images. You would typically use these icons as the custom image for a button, or you might apply them to a cell in a control. For example, you might use the NSImageNameIconViewTemplate image to indicate an item is not modifiable. Template images should use black and clear colors only and it is fine to include varying levels of alpha.

You should use these images in conjunction with the buttons (usually part of a segmented control) that change the current viewing mode. The appearance of images can change between releases. If you use an image for its intended purpose (and not because of how it looks), your code should look correct from release to release.

The size and aspect ratio of system images may change from release to release. In some situations, you should explicitly resize images as appropriate for your use. If you use these images in conjunction with an NSButtonCell object, however, you can use the setImageScaling: method of the cell to control scaling instead. Similarly, for an NSSegmentedCell object, you can use the setImageScaling:forSegment: method to control scaling.

The string value for each constant is equal to the constant name without the “ImageName” portion. You might need this information to locate images by name in Interface Builder. For example, the constant NSImageNameFlowViewTemplate would correspond to an image named “NSFlowViewTemplate” in Interface Builder.

Declared In
NSImage.h