2011-09-29 92 views
2

我试图将文件的图标更改为NSView的表示形式。我正在使用下面的代码来做到这一点。保存NSView表示忽略透明度

[mainDisplay lockFocus]; 
    NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[mainDisplay bounds]]; 
    [mainDisplay unlockFocus]; 
    NSImage *image = [[NSImage alloc] initWithData:[rep representationUsingType:NSTIFFFileType properties:nil]]; 
    [[NSWorkspace sharedWorkspace] setIcon:image forFile:[savePanel filename] options:0]; 

This works。它改变了图标的样子,除了白色的任何透明度。我怎样才能保持透明度?我知道它适用于Photoshop,但是可以使用Apple的框架吗?

回答

4

这种方式不能获得透明的图像,因为[NSBitmapImageRep initWithFocusedViewRect:]从窗口服务器获取一幅渲染图像,其中视图的图像已经平铺为具有其他下层视图和窗口背景的图像。

你需要的是它以适当的格式分配一个新的清洁NSBitmapImageRep和渲染视图的上它的内容:

NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil 
pixelsWide:[mainDisplay bounds].size.width pixelsHigh:[mainDisplay bounds].size.height 
bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO 
colorSpaceName:NSDeviceRGBColorSpace 
bytesPerRow:[mainDisplay bounds].size.width * 4 bitsPerPixel:32]; 

[mainDisplay cacheDisplayInRect:[mainDisplay bounds] toBitmapImageRep:rep]; 
+0

感谢。我会立即尝试。有没有什么办法可以减少这段代码的内存使用量(不是说效率不高)?编辑:这太棒了!非常感谢!我一定想知道提高效率的方法,但是,由于我原来的代码效率不高,所以没有必要。 – Justin

+0

使用工具来调整效率。在为文件设置图标后立即释放“rep”和“image”。此外,如果您在循环中使用它来处理许多文件,请尝试不要自动释放它们,请使用正常版本。 – Davyd

+0

您可以并应该发送视图[a'bitmapImageRepForCachingDisplayInRect:'message](http://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/Reference/NSView.html#//apple_ref/occ/instm/NSView/bitmapImageRepForCachingDisplayInRect:')来创建代表。除了更简单之外,文档还表明这对于“像素格式兼容性”非常重要。 –