更改NSWindow边框颜色

时间:2013-02-06 01:58:58

标签: objective-c macos cocoa

我需要更改应用的NSWindow周围的边框颜色。

有谁知道窗口边框的绘制位置,如何更改颜色/覆盖绘制边框的方法?

我注意到Tweetbot这样做了:

Regular border vs Tweetbot border

1 个答案:

答案 0 :(得分:2)

从内存来看,我认为Tweetbot使用了一个完整的无边框窗口,并添加了窗口控件本身,但如果你想让AppKit仍然处理这些细节,还有另一种方法。如果将窗口设置为纹理窗口,则可以设置自定义背景NSColor。此NSColor可以是使用+[NSColor colorWithPatternImage:]

的图像

作为一个例子,我快速敲了这个,只是使用纯灰色作为填充,但你可以在这个图像中绘制任何你喜欢的东西。然后,您只需要将NSWindow的类类型设置为纹理窗口类。

SLFTexturedWindow.h

@interface SLFTexturedWindow : NSWindow
@end

SLFTexturedWindow.m

#import "SLFTexturedWindow.h"

@implementation SLFTexturedWindow

- (id)initWithContentRect:(NSRect)contentRect
                styleMask:(NSUInteger)styleMask
                  backing:(NSBackingStoreType)bufferingType
                    defer:(BOOL)flag;
{
    NSUInteger newStyle;
if (styleMask & NSTexturedBackgroundWindowMask) {
    newStyle = styleMask;
} else {
    newStyle = (NSTexturedBackgroundWindowMask | styleMask);
}

if (self = [super initWithContentRect:contentRect styleMask:newStyle backing:bufferingType defer:flag]) {

    [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(windowDidResize:)
                                                     name:NSWindowDidResizeNotification
                                                   object:self];

        [self setBackgroundColor:[self addBorderToBackground]];

        return self;
}

return nil;
}

- (void)windowDidResize:(NSNotification *)aNotification
{
    [self setBackgroundColor:[self addBorderToBackground]];
}

- (NSColor *)addBorderToBackground
{
    NSImage *bg = [[NSImage alloc] initWithSize:[self frame].size];
    // Begin drawing into our main image
[bg lockFocus];

[[NSColor lightGrayColor] set];
NSRectFill(NSMakeRect(0, 0, [bg size].width, [bg size].height));

    [[NSColor blackColor] set];

    NSRect bounds = NSMakeRect(0, 0, [self frame].size.width, [self frame].size.height);
    NSBezierPath *border = [NSBezierPath bezierPathWithRoundedRect:bounds xRadius:3 yRadius:3];
    [border stroke];

    [bg unlockFocus];

    return [NSColor colorWithPatternImage:bg];  
}

@end