保存NSView表示忽略透明度 [英] Save NSView representation ignores transparency

查看:85
本文介绍了保存NSView表示忽略透明度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文件的图标更改为 NSView 的表示形式。我正在使用以下代码来做到这一点。

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

这有效。它将图标完全更改为我想要的颜色,但任何透明性都变为白色。如何保持透明度?我知道它适用于Photoshop,但是可以使用Apple的框架吗?

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?

推荐答案

您无法通过这种方式获得具有透明度的图像,因为 [NSBitmapImageRep initWithFocusedViewRect:] 从窗口服务器获取一块渲染的图像,该视图的图像已经被平整为具有其他底层视图和窗口背景的图像。

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.

您需要的是分配一个具有适当格式的干净的 NSBitmapImageRep 并在其上呈现视图的内容:

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

这篇关于保存NSView表示忽略透明度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆