簡體   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