Class

NSImage

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.

Overview

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

  • Loading images stored on disk or at a specified URL.

  • Drawing images into a view or graphics context.

  • Providing the contents of a CALayer object.

  • Creating new images based on a series of captured drawing commands.

  • Producing versions of the image in a different format.

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 layerContents(forContentsScale:) 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 layerContents(forContentsScale:) 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];
}

Symbols

Initializing a New NSImage Object

init?(byReferencingFile: String)

Initializes and returns an image object using the specified file.

init(byReferencing: URL)

Initializes and returns an image object using the specified URL.

init(cgImage: CGImage, size: NSSize)

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

init?(contentsOfFile: String)

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

init?(contentsOf: URL)

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

init?(data: Data)

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

init?(dataIgnoringOrientation: Data)

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

init?(pasteboard: NSPasteboard)

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

init(size: NSSize, flipped: Bool, drawingHandler: (NSRect) -> Bool)

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

init(size: NSSize)

Initializes and returns an image object with the specified dimensions.

init(iconRef: IconRef)

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

Referring to Images by Name

init?(named: String)

Returns the image object associated with the specified name.

func setName(String?)

Registers the receiver under the specified name.

func name()

Returns the name associated with the receiver, if any.

Setting the Image Attributes

var size: NSSize

The size of the receiver.

isTemplate

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

var isTemplate: Bool

Sets whether the image represents a template image.

Determining the Supported Image Types

class func canInit(with: NSPasteboard)

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

class func 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.

class func imageUnfilteredTypes()

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

class func imageFileTypes()

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

Deprecated
class func imageUnfilteredFileTypes()

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

Deprecated
class func imagePasteboardTypes()

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

Deprecated
class func imageUnfilteredPasteboardTypes()

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

Deprecated

Working With Image Representations

func addRepresentation(NSImageRep)

Adds the specified image representation object to to the receiver.

func addRepresentations([NSImageRep])

Adds an array of image representation objects to the receiver.

var representations: [NSImageRep]

An array containing all of the receiver's image representations.

func removeRepresentation(NSImageRep)

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

func bestRepresentation(for: NSRect, context: NSGraphicsContext?, hints: [String : Any]?)

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

Setting the Image Representation Selection Criteria

var prefersColorMatch: Bool

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

var usesEPSOnResolutionMismatch: Bool

A Boolean value that indicates whether EPS representations are preferred when no other representations match the resolution of the device.

var matchesOnMultipleResolution: Bool

A Boolean value that indicates whether image representations whose resolution is an integral multiple of the device resolution are considered a match.

Drawing the Image

func draw(in: NSRect)

Draws the image in the specified rectangle.

func draw(at: NSPoint, from: NSRect, operation: NSCompositingOperation, fraction: CGFloat)

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

func draw(in: NSRect, from: NSRect, operation: NSCompositingOperation, fraction: CGFloat)

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

func draw(in: NSRect, from: NSRect, operation: NSCompositingOperation, fraction: CGFloat, respectFlipped: Bool, hints: [String : Any]?)

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

func drawRepresentation(NSImageRep, in: NSRect)

Draws the image using the specified image representation object.

Managing the Drawing Options

var isValid: Bool

A Boolean value that indicates whether an image representation from the receiver can be drawn.

var backgroundColor: NSColor

The background color for the image.

Managing the Focus

func lockFocus()

Prepares the image to receive drawing commands.

func lockFocusFlipped(Bool)

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

func unlockFocus()

Removes the focus from the receiver.

Working With Alignment Metadata

var alignmentRect: NSRect

A rectangle that your code can use to position the image during layout.

Managing the Caching Options

var cacheMode: NSImageCacheMode

The image’s caching mode.

func recache()

Invalidates and frees the offscreen caches of all image representations.

Accessing the Delegate

var delegate: NSImageDelegate?

The image’s delegate object.

Producing TIFF Data for the Image

var tiffRepresentation: Data?

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

func tiffRepresentation(using: NSTIFFCompression, factor: Float)

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

Producing a CGImage from an Image

Managing Incremental Loads

func cancelIncrementalLoad()

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

Hit Testing an Image

func hitTest(NSRect, withDestinationRect: NSRect, context: NSGraphicsContext?, hints: [String : Any]?, flipped: Bool)

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

Managing Image Accessibility

var accessibilityDescription: String?

The image’s accessibility description.

Using an Image with Core Animation

func layerContents(forContentsScale: CGFloat)

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

func recommendedLayerContentsScale(CGFloat)

Returns the recommended layer contents scale for this image.

Managing Axis Matching

var matchesOnlyOnBestFittingAxis: Bool

A Boolean value that indicates whether the image matches only on the best fitting axis.

Constants

Image Hint Dictionary Keys

These constants are a subset of the dictionary keys used in the hints dictionary for the methods cgImage(forProposedRect:context:hints:), bestRepresentation(for:context:hints:), draw(in:from:operation:fraction:respectFlipped:hints:), and hitTest(_:withDestinationRect: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.

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.

NSImageLoadStatus

These constants are status values passed to the incremental loading delegate method image(_:didLoadRepresentation:with:).

NSImageCacheMode

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

Image Template Constants

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

Multiple Documents Drag Image

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

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 init(named:) method.

System Entity Images

Images representing Finder items. To access this image, pass the specified constant to the init(named:) method.

Toolbar Named Images

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

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 init(named:) method.