繁体   English   中英

在可可中获取桌面背景

[英]Getting Desktop Background in Cocoa

我需要做一些全屏应用程序,通常这不是问题。 现在的问题是,我需要拥有用户桌面,但没有图标作为全屏窗口的背景,就像10.7中的启动板一样。 我已经参考了AppleScript中的桌面背景:

tell application "Finder"
    set a to desktop picture
end tell

这给了我类似的信息: document file "100930-F-7910D-001.jpg" of folder "Pictures" of folder "Fighter Jet Stuff" of folder "Desktop" of folder "tristan" of folder "Users" of startup disk of application "Finder"我根本想不通的document file "100930-F-7910D-001.jpg" of folder "Pictures" of folder "Fighter Jet Stuff" of folder "Desktop" of folder "tristan" of folder "Users" of startup disk of application "Finder"

我尝试set a to desktop picture as POSIX path但这使我不安。 是否知道如何使用上述Applescript在Cocoa中做到这一点,或者甚至在没有Applescript的情况下做到这一点呢? 我不想依赖任何可能存储此信息的plist的特定格式,因为它有可能在以后中断。 我在想可能会有一个我不知道的框架...

NSWorkspace中提供了您要寻找的方法。

– desktopImageURLForScreen:
– setDesktopImageURL:forScreen:options:error:
– desktopImageOptionsForScreen:

请在此处查看文档: NSWorkspace类参考

如果仅需要当前墙纸,则可以对其截图:

extension NSImage {

    static func desktopPicture() -> NSImage {

        let windows = CGWindowListCopyWindowInfo(
            CGWindowListOption.OptionOnScreenOnly,
            CGWindowID(0))! as NSArray

        var index = 0
        for var i = 0; i < windows.count; i++  {
            let window = windows[i]

            // we need windows owned by Dock
            let owner = window["kCGWindowOwnerName"] as! String
            if owner != "Dock" {
                continue
            }

            // we need windows named like "Desktop Picture %"
            let name = window["kCGWindowName"] as! String
            if !name.hasPrefix("Desktop Picture") {
                continue
            }

            // wee need the one which belongs to the current screen
            let bounds = window["kCGWindowBounds"] as! NSDictionary
            let x = bounds["X"] as! CGFloat
            if x == NSScreen.mainScreen()!.frame.origin.x {
                index = window["kCGWindowNumber"] as! Int
                break
            }
        }

        let cgImage = CGWindowListCreateImage(
            CGRectZero,
            CGWindowListOption(arrayLiteral: CGWindowListOption.OptionIncludingWindow),
            CGWindowID(index),
            CGWindowImageOption.Default)!

        let image = NSImage(CGImage: cgImage, size: NSScreen.mainScreen()!.frame.size)
        return image
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM