gpt4 book ai didi

cocoa - 获取 Cocoa 中的当前壁纸

转载 作者:行者123 更新时间:2023-12-03 16:05:27 24 4
gpt4 key购买 nike

我使用此代码来获取当前壁纸:

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

这工作正常,但是当我将图片文件夹设置为壁纸时(如图所示),imageURL是一个目录,那么我如何获取当前壁纸的USURL这种情况?

enter image description here

最佳答案

还有另一种获取图像的方法,即截取当前壁纸的屏幕截图。

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

如果您需要图片而不是网址,则这种方法看起来要简单得多。

请注意,壁纸不再在 com.apple.dektop plist 中定义:从 Mavericks 开始,该设置已移至 ~/Library/Application Support/Dock/desktoppicture.db。这是 SQLite 文件,“数据”表包含 url。

关于cocoa - 获取 Cocoa 中的当前壁纸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14099363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com