将NSView子类化为具有透明背景

时间:2023-01-24 08:59:37

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(只要我可以在里面添加子视图,我需要在里面添加一些文本)。

3 个解决方案

#1


16  

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的子类而不是其他视图,则无需担心覆盖它。

#2


10  

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
}

#3


0  

The Swift version:

Swift版本:

override func draw(_ dirtyRect: NSRect) {

    NSColor.clear.set()
    dirtyRect.fill()
}

#1


16  

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的子类而不是其他视图,则无需担心覆盖它。

#2


10  

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
}

#3


0  

The Swift version:

Swift版本:

override func draw(_ dirtyRect: NSRect) {

    NSColor.clear.set()
    dirtyRect.fill()
}