NSWindow with round corners and shadow

后端 未结 11 1868
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-23 02:26

I\'m trying to crate a NSWindow without title bar (NSBorderlessWindowMask) with round corners and a shadow, similar to the below \"Welcome

11条回答
  •  悲哀的现实
    2020-12-23 03:07

    You have two options:

    1. Use the layer's shadow properties.
    2. Draw the shadow yourself in your drawRect routine. For this to work don't set the rounded corners but use an inset path to draw the rounded rectangle and its shadow.

    Code:

    @interface RoundedOuterShadowView : NSView {
    }
    
    @end
    
    @implementation RoundedOuterShadowView
    
    - (id)initWithFrame: (NSRect)frameRect
    {
        self = [super initWithFrame: frameRect];
        if (self != nil) {
        }
    
        return self;
    }
    
    // Shared objects.
    static NSShadow *borderShadow = nil;
    
    - (void)drawRect: (NSRect)rect
    {
        [NSGraphicsContext saveGraphicsState];
    
        // Initialize shared objects.
        if (borderShadow == nil) {
            borderShadow = [[NSShadow alloc] initWithColor: [NSColor colorWithDeviceWhite: 0 alpha: 0.5]
                                                    offset: NSMakeSize(1, -1)
                                                blurRadius: 5.0];
        }
    
        // Outer bounds with shadow.
        NSRect bounds = [self bounds];
        bounds.size.width -= 20;
        bounds.size.height -= 20;
        bounds.origin.x += 10;
        bounds.origin.y += 10;
    
        NSBezierPath *borderPath = [NSBezierPath bezierPathWithRoundedRect: bounds xRadius: 5 yRadius: 5];
        [borderShadow set];
        [[NSColor whiteColor] set];
        [borderPath fill];
    
        [NSGraphicsContext restoreGraphicsState];
    }
    
    @end
    

提交回复
热议问题