Save NSView representation ignores transparency

会有一股神秘感。 提交于 2019-12-13 15:42:00

问题


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]];
    [[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?


回答1:


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];


来源:https://stackoverflow.com/questions/7604287/save-nsview-representation-ignores-transparency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!