NSWorkspace setDesktopImageURL 适合屏幕

NSWorkspace setDesktopImageURL fit to screen

目前,我有这个。

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

当我将我的图像设置为桌面墙纸时,在系统偏好设置中检查时图像默认为 "fill screen" 选项。我希望将其设置为 "fit to screen" 选项 - 有什么方法可以做到这一点吗?

您可以通过在屏幕的选项字典中为键 NSWorkspaceDesktopImageScalingKey 设置 NSImageScaling.scaleProportionallyUpOrDown 来获得 "size to fit" 行为。

Swift3 中的示例:

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