0

我尝试获取一个文件图标并将其设置回同一个文件(目标是覆盖,但我首先想让这个工作):

NSImage *img=[[NSWorkspace sharedWorkspace] iconForFile:@"MyFilePath"];
NSLog(@"x=%.f",img.size.width); // Result=32
[[NSWorkspace sharedWorkspace] setIcon:img forFile:@"MyFilePath" options:0];

-> 结果是我的文件获得了标准的 Finder 图标,而不是保留自己的图标。有什么我做错了吗?

4

1 回答 1

0

Try using it like this:

[[NSWorkspace sharedWorkspace]
              setIcon: [[NSImage alloc] initWithContentsOfFile:@"MyFilePath"]
              forFile: @"MyFilePath"
              options: 0];

You need to to load the icon/image into memory first.

EDIT: Answer updated to provide additional information in regards to the comment below.

"how can I keep the image in memory to "play" with it before reassigning it?"

The NSImage that gets allocated into memory from your specified path can be manipulated in just about any possible way once it's been loaded. You'll want to thoroughly read the NSImage Class Reference to gain a real understanding of what it does and how use it's methods. For this particular scenario you'll want to be able have a named variable assigned from the icon you load.

Only one change needs to happen with the code above to make it work:

NSImage *iconImage = [[NSImage alloc] initWithContentsOfFile:@"MyFilePath"];

[[NSWorkspace sharedWorkspace]
                setIcon: iconImage
                forFile: @"MyFilePath"
                options: 0];

NSLog(@"iconImage: %@",iconImage);

The slight change essentially assigns the variable iconImage from the NSImage icon; everything else stays the same. The NSLog will give you a very quick glimpse at properties associated with iconImage — where you take it from there is really up to your coding ability and creativity.

于 2014-03-19T19:03:22.063 回答