我正在使用此代码获取当前壁纸:
NSURL *imageURL = [[NSWorkspace sharedWorkspace] desktopImageURLForScreen:[NSScreen mainScreen]];
这很好用,但是当我将图片文件夹设置为壁纸时(如图所示),imageURL
是一个目录,那么在这种情况下如何获得当前壁纸的USURL?
答案 0 :(得分:3)
我一直在尝试做同样的事情。 您可以通过以下方式获取当前桌面图片URL:
我仍在努力解决此问题,但以下代码有时会获得正确的网址。 主要问题是属性列表没有经常更新,我无法强制刷新(没有杀死停靠)。如果你搞清楚了,请告诉我!
NSDictionary *spacesPLIST = (__bridge NSDictionary *)(CFPreferencesCopyAppValue(CFSTR("SpacesConfiguration"), CFSTR("com.apple.spaces")));
NSDictionary *desktopPLIST = (__bridge NSDictionary *)(CFPreferencesCopyAppValue(CFSTR("Background"), CFSTR("com.apple.desktop")));
NSArray *monitors = [spacesPLIST valueForKeyPath:@"Management Data.Monitors"];
NSInteger monitorIndex = 0;
if ([monitors count] > 1) {
//search for main (or ask user to select)
}
NSDictionary *monitor = [monitors objectAtIndex:monitorIndex];
NSDictionary *spaces = [desktopPLIST valueForKey:@"spaces"];
NSString *currentSpaceUUID = [monitor valueForKeyPath:@"Current Space.uuid"];
NSDictionary *currentSpace = [spaces valueForKey:currentSpaceUUID];
NSURL *desktopPicturesDirectory = [NSURL fileURLWithPath:[currentSpace valueForKeyPath:@"default.ChangePath"] isDirectory:true];
NSString *desktopPictureName = [currentSpace valueForKeyPath:@"default.LastName"];
NSURL *desktopPictureURL = [NSURL URLWithString:desktopPictureName relativeToURL:desktopPicturesDirectory];
[[NSWorkspace sharedWorkspace] selectFile:[desktopPictureURL path] inFileViewerRootedAtPath:@""];
答案 1 :(得分:3)
还有另一种方法可以通过拍摄当前壁纸的截图来获取图像。
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文件,“data”表包含url。