Get the current wallpaper in Cocoa

前端 未结 2 735
深忆病人
深忆病人 2020-12-31 15:29

I\'m using this code to get the current wallpaper:

NSURL *imageURL = [[NSWorkspace sharedWorkspace] desktopImageURLForScreen:[NSScreen mainScreen]];
<         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 16:27

    There is another way to get the image by taking a screenshot of the current wallpaper.

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

    This approach looks much simpler IMHO, if you need the picture, not the url.

    Note that wallpaper is no longer defined in the com.apple.dektop plist: starting from Mavericks, the setting is moved to ~/Library/Application Support/Dock/desktoppicture.db. This is SQLite file, and the "data" table contains the url.

提交回复
热议问题