开发者

Save NSView representation ignores transparency

I am trying to change the icon of a file to a representation of an NSView. I am using the following code to do so.

    [mainDisplay lockFocus];
    NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[mainDisplay bounds]];
    [mainDisplay unlockFocus];
    NSImage *image = [[NSImage alloc] initWithData:[rep representationUsingType:NSTIFFFileType properties:nil]];
 开发者_如何学JAVA   [[NSWorkspace sharedWorkspace] setIcon:image forFile:[savePanel filename] options:0];

This works. It changes the icon exactly how I would like, except for the fact that any transparency to white. How can I keep the transparency? I know it works for Photoshop, but is is possible using Apple's frameworks?


You cannot get an image with transparency this way, because [NSBitmapImageRep initWithFocusedViewRect:] gets a piece of rendered image from the window server, where the view's image already flattened to an image with other underlaying views and the window's background.

What you need is it to allocate a new clean NSBitmapImageRep with appropriate format and render the view's content on it:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜