skywang329
skywang329

Reputation: 49

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?

Upvotes: 1

Views: 781

Answers (2)

nramirez
nramirez

Reputation: 5630

Bringing this from the comments for visibility purposes, .imageScaling expects an NSNumber.

This is how it looks:

var options: [NSWorkspace.DesktopImageOptionKey: Any] = [:]
let scaleString: String = opts["scale"] as! String
if scaleString == "fill" {
       options[.imageScaling] = NSNumber(value: NSImageScaling.scaleAxesIndependently.rawValue)
    } else if scaleString == "fit" {
        options[.imageScaling] = NSNumber(value:NSImageScaling.scaleProportionallyUpOrDown.rawValue)
    } else if scaleString == "stretch" {
        options[.imageScaling] = NSNumber(value:NSImageScaling.scaleAxesIndependently.rawValue)
    } else if scaleString == "center" {
        options[.imageScaling] = NSNumber(value:NSImageScaling.scaleNone.rawValue)
    } else {
        options[.imageScaling] = NSNumber(value:NSImageScaling.scaleProportionallyUpOrDown.rawValue)
    }

try NSWorkspace.shared.setDesktopImageURL(destinationURL, for: NSScreen.main!, options: options)

props to @Eric Aya for the comment.

Upvotes: 0

Eric Aya
Eric Aya

Reputation: 70115

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)
}

Upvotes: 0

Related Questions