swiftmacoscocoawallpapernsworkspace

NSWorkspace setDesktopImageURL fit to screen


Currently, I have this.

var workspace = NSWorkspace.shared()    
do {
    try workspace.setDesktopImageURL(destinationURL, for: screen, options: [:])
} catch {}

When I set my image as the desktop wallpaper, the image defaults to the "fill screen" option when checked in system preferences. I would like it to be set to the "fit to screen" option - any way to do this?


Solution

  • You can get the "size to fit" behavior by setting NSImageScaling.scaleProportionallyUpOrDown for the key NSWorkspaceDesktopImageScalingKey in the screen's options dictionary.

    Example in Swift 3:

    do {
        // here we use the first screen, adapt to your case
        guard let screens = NSScreen.screens(),
            let screen = screens.first else
        {
            // handle error if no screen is available
            return
        }
        let workspace = NSWorkspace.shared()
        // we get the screen's options dictionary in a variable
        guard var options = workspace.desktopImageOptions(for: screen) else {
            // handle error if no options dictionary is available for this screen
            return
        }
        // we add (or replace) our options in the dictionary
        // "size to fit" is NSImageScaling.scaleProportionallyUpOrDown
        options[NSWorkspaceDesktopImageScalingKey] = NSImageScaling.scaleProportionallyUpOrDown
        options[NSWorkspaceDesktopImageAllowClippingKey] = true
        // finally we write the image using the new options
        try workspace.setDesktopImageURL(destinationURL, for: screen, options: options)
    } catch {
        print(error.localizedDescription)
    }