macos 子类化 NSView 以获得透明背景
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4635442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Subclassing NSView to have a transparent background
提问by Andrew M
I am creating an app where I need to have a transparent NSView with a transparent PNG image inside. The problem is, the NSView I'm drawing has a gray background on it. I have it subclassed (as TransparentRectangleView) but don't know what to put in drawRect to make it transparent.
我正在创建一个应用程序,我需要一个透明的 NSView,里面有一个透明的 PNG 图像。问题是,我正在绘制的 NSView 有灰色背景。我将它子类化(如 TransparentRectangleView),但不知道在 drawRect 中放入什么以使其透明。
I have already overridden the isOpaque method to return NO but it doesn't seem to help...
我已经覆盖了 isOpaque 方法来返回 NO 但它似乎没有帮助......
Alternatively, is there already a subclassed NSView that is similar to the iPhone's UIImageView (as long as I can add subviews inside, I need to add some text inside).
或者,是否已经有一个类似于 iPhone 的 UIImageView 的子类 NSView(只要我可以在里面添加子视图,我需要在里面添加一些文本)。
回答by ughoavgfhw
To make a view transparent, simply fill it with [NSColor clearColor].
要使视图透明,只需用 [NSColor clearColor] 填充它。
- (void)drawRect:(NSRect)rect {
[[NSColor clearColor] set];
NSRectFill(rect);
}
The default implementation of isOpaque returns NO, so if you are subclassing NSView and not some other view you don't need to worry about overriding it.
isOpaque 的默认实现返回 NO,所以如果你子类化 NSView 而不是其他一些视图,你不需要担心覆盖它。
回答by lk_vc
The accepted answer does not work for me since mine window is opaque. As http://www.drissman.com/blog/archives/2009/10/09/nsrectfill_and_nscolor_clearcolor.html(and the discussion below) said, the following codes work:
接受的答案对我不起作用,因为我的窗口是不透明的。正如http://www.drissman.com/blog/archives/2009/10/09/nsrectfill_and_nscolor_clearcolor.html(以及下面的讨论)所说,以下代码有效:
- (void)drawRect:(NSRect)rect {
[[NSColor clearColor] set];
NSRectFillUsingOperation(rect, NSCompositeSourceOver);
// do other drawings
}
回答by sebastienhamel
The Swift version:
斯威夫特版本:
override func draw(_ dirtyRect: NSRect) {
NSColor.clear.set()
dirtyRect.fill()
}