Rounded NSView in a Transparent Window

坚强是说给别人听的谎言 提交于 2019-12-06 05:35:21

问题


I'm trying to make a transparent NSWindow with a rounded view in there.

I'm trying to have a rounded view with a transparent window.

This is what it looks like now: (see the little dots in the corners)

Here's another example with the border radius set to 10px (set in NSView drawRect):

I am using code from this Apple sample: https://developer.apple.com/library/mac/#samplecode/RoundTransparentWindow/Introduction/Intro.html

Specifically this method in my NSWindow subclass:

- (id)initWithContentRect:(NSRect)contentRect
                styleMask:(NSUInteger)aStyle
                  backing:(NSBackingStoreType)bufferingType
                    defer:(BOOL)flag {
    // Using NSBorderlessWindowMask results in a window without a title bar.
    self = [super initWithContentRect:contentRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO];
    if (self != nil) {
        // Start with no transparency for all drawing into the window
        [self setAlphaValue:1.0];
        // Turn off opacity so that the parts of the window that are not drawn into are transparent.
        [self setOpaque:NO];
    [self setBackgroundColor:[NSColor clearColor]];

    }
    return self;
}

And this in my NSView subclass:

- (void)drawRect:(NSRect)dirtyRect
{
    [[NSColor redColor] set];
    NSBezierPath* thePath = [NSBezierPath bezierPath];
    [thePath appendBezierPathWithRoundedRect:dirtyRect xRadius:3 yRadius:3];
    [thePath fill];
}

Can anyone tell me what I'm missing here?

Thanks.


回答1:


Are you looking for something like the following, where there's a red outline (stroke), but the center area is transparent?

If so, to achieve that, I used the following code:

- (void)drawRect:(NSRect)frame {
    frame = NSInsetRect(self.frame, 3.0, 3.0);

    [NSBezierPath setDefaultLineWidth:6.0];

    NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:frame
                                             xRadius:6.0 yRadius:6.0];
    [[NSColor redColor] set];
    [path stroke];
}

If that's what you're looking for, you can probably use that as a starting point. You'll want to make sure that you inset the frame rect one half of the stroke line width, so as to avoid the problem with clipping the corners like you were seeing.




回答2:


Not sure if this is what you are looking for but there is a great class by Matt Gemmell called MAAttachedWindow and can be found here: http://mattgemmell.com/2007/10/03/maattachedwindow-nswindow-subclass/

It's a little older but still works great for me when I need to do a 'floating' popup window and configure transparency, border radii, and even add a small arrow for context if desired. I use it all the time.



来源:https://stackoverflow.com/questions/15007580/rounded-nsview-in-a-transparent-window

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