Subclassing NSView to have a transparent background

♀尐吖头ヾ 提交于 2019-12-18 04:45:07

问题


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.

I have already overridden the isOpaque method to return NO but it doesn't seem to help...

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).


回答1:


To make a view transparent, simply fill it with [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.




回答2:


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:

- (void)drawRect:(NSRect)rect {
    [[NSColor clearColor] set];
    NSRectFillUsingOperation(rect, NSCompositeSourceOver);
    // do other drawings
}



回答3:


The Swift version:

override func draw(_ dirtyRect: NSRect) {

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


来源:https://stackoverflow.com/questions/4635442/subclassing-nsview-to-have-a-transparent-background

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