获取另一个尺寸的 NSRunningApplication 图标

Get NSRunningApplication's icon with an other size

// 561 is PID of Chrome application in Activity Monitor.
NSRunningApplication *chromeApp = [NSRunningApplication runningApplicationWithProcessIdentifier:561];
self.imgView.image = chromeApp.icon;

我的日志:

(lldb) po chromeApp.icon
<NSImage 0x608000268c40 Size={32, 32} Reps=(
    "<NSIconRefImageRep:0x600000082df0 iconRef=0x103 size:128x128 pixels:128x128>",
    "<NSIconRefImageRep:0x600000083020 iconRef=0x103 size:128x128 pixels:256x256>",
    "<NSIconRefImageRep:0x600000082fd0 iconRef=0x103 size:256x256 pixels:256x256>",
    "<NSIconRefImageRep:0x600000083070 iconRef=0x103 size:256x256 pixels:512x512>",
    "<NSIconRefImageRep:0x6000000830c0 iconRef=0x103 size:512x512 pixels:512x512>",
    "<NSIconRefImageRep:0x600000083110 iconRef=0x103 size:48x48 pixels:48x48>",
    "<NSIconRefImageRep:0x600000083160 iconRef=0x103 size:36x36 pixels:36x36>",
    "<NSIconRefImageRep:0x600000083200 iconRef=0x103 size:36x36 pixels:72x72>",
    "<NSIconRefImageRep:0x600000083250 iconRef=0x103 size:32x32 pixels:32x32>",
    "<NSIconRefImageRep:0x6000000832a0 iconRef=0x103 size:32x32 pixels:64x64>",
    "<NSIconRefImageRep:0x6000000832f0 iconRef=0x103 size:18x18 pixels:18x18>",
    "<NSIconRefImageRep:0x6000000831b0 iconRef=0x103 size:18x18 pixels:36x36>",
    "<NSIconRefImageRep:0x600000083340 iconRef=0x103 size:16x16 pixels:16x16>",
    "<NSIconRefImageRep:0x600000083390 iconRef=0x103 size:16x16 pixels:32x32>",
    "<NSIconRefImageRep:0x6000000833e0 iconRef=0x103 size:512x512 pixels:1024x1024>"
)>

在上面的代码中,我收到了一张尺寸为 32x32 的图像(在我的 xib 文件中,imageView 的尺寸为 la 512 x 512)。 问题:如何获取512x512像素的图片。

在这个答案中,我尝试在 Safari 中使用它(而不是 Chrome),因为我不知道 Chrome 的 bundleIdentifier。以下代码包含一些用于测试的 NSLog,但没有错误处理和内存管理:

获取 NSRunningApplication:

NSArray *appArray =
        [NSRunningApplication 
            runningApplicationsWithBundleIdentifier:@"com.apple.Safari"];
NSLog(@"%@", appArray );
NSRunningApplication *safariApp = [appArray objectAtIndex:0];

首先加载应用程序的图标:

NSImage *iconImage = safariApp.icon;
NSLog( @"iconImage:\n%@", ); //show all representations

然后提取最适合您的 NSImageView 的 NSImageRep:

NSRect rect = [myImageView frame];
NSLog( @"rect = %@", NSStringFromRect( rect ) );
NSImageRep *rep = [iconImage bestRepresentationForRect:rect
                                               context:nil
                                                 hints:nil];
NSLog( @"rep = %@", );  // what rep is selected?
// make an NSImage from this rep
NSImage *theImage = [[NSImage alloc] initWithSize:NSZeroSize];
[theImage addRepresentation:rep];
self.imgView.image = theImage;

在您的示例中(使用大小为 512x512 的 imageView),将选择大小为 512x512 像素=512x512 的代表。如果你有视网膜屏幕,你会得到 size=512x512 pixels=1024x1024 的代表。

您返回的图标是一个 NSImage,其大小设置为 32x32。意味着如果你现在绘制它,它会选择一个合适的 NSImageRepresentation。从日志中可以看到它有很多不同的 - 它们是不同的数据

所以你需要做的就是:

self.imgView.image.size = NSMakeSize(512,512);

一个 NSImage 基本上只是一个 'drawable',它没有自己的数据,但它 'groups' 在一起

的图像数据的 1..n 表示