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.
- macOS 10.10+
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
Creating new images based on a series of captured drawing commands.
Producing versions of the image in a different format.
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
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.