2
votes

I have a subclass of NSWindow to customize one of my windows for my app. I have everything set, but I am not sure how to make the corners round. Currently, my window is a transparent rectangular window with some buttons, labels, and a textfield in it.

The class includes:

#import "TransparentRoundRectWindow.h"

@implementation TransparentRoundRectWindow

-(id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)aStyle backing:(NSBackingStoreType)bufferingType defer:(BOOL)flag
{
    self = [super initWithContentRect:contentRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO];
    if (self) {
        [self setAlphaValue:0.75];
        [self setOpaque:YES];
        [self setHasShadow:YES];
        [self setBackgroundColor:[NSColor clearColor]];
    }
    return self;
}

-(BOOL)canBecomeKeyWindow
{
    return YES;
}

I just need to make the corners round now. I tried searching for similar situations and saw some of them explaining to override the drawRect method but I couldn't get them to work. How could I do this? (I'm using Mac OS X Lion)

Thanks in advance.

1

1 Answers

7
votes

You need to set to Your window Opaque to NO. And subclass Your window's view.

Window subclass:

-(id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)aStyle backing:(NSBackingStoreType)bufferingType defer:(BOOL)flag
{
    self = [super initWithContentRect:contentRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO];
    if (self) {

        [self setOpaque:NO];
        [self setHasShadow:YES];
        [self setBackgroundColor:[NSColor clearColor]];
    }
    return self;
}

-(BOOL)canBecomeKeyWindow
{
    return YES;
}

Window's view subclass:

- (void)drawRect:(NSRect)rect
{
    NSBezierPath * path;
    path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:8 yRadius:8];

    [[NSColor colorWithCalibratedRed:0 green:0 blue:0 alpha:0.75] set];
    [path fill];
}

Result:

result

More explanation how to do this:

Create new NSView class and paste "Window's view subclass" code which I wrote in it. Then go to Your window's view.

Here is window's view click on it:

Window's view

Go to the Identity inspector and set class to your created class:

enter image description here