swift NSWorkspace setDesktopImageURL适合屏幕

ldxq2e6h  于 2023-03-28  发布在  Swift
关注(0)|答案(2)|浏览(122)

目前,我有这个。

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

当我将我的图像设置为桌面壁纸时,在系统首选项中选中时,图像默认为“填充屏幕”选项。我想将其设置为“适合屏幕”选项-有什么方法可以做到这一点?

qv7cva1a

qv7cva1a1#

您可以通过在屏幕的选项字典中为键NSWorkspaceDesktopImageScalingKey设置NSImageScaling.scaleProportionallyUpOrDown来获得“适合大小”行为。
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)
}
yuvru6vn

yuvru6vn2#

出于可见性目的,.imageScaling需要一个NSNumber。
它看起来是这样的:

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)

@Eric Aya评论

相关问题