6

我正在尝试用渐变填充 NSView。当窗口在背景中时,渐变应该具有较浅的颜色以匹配窗口的其余部分。下面的代码有很多人工制品:当第一次绘制窗口时,它是用背景颜色绘制的。调整窗口大小时,将使用前景色。当窗口移到后面时,背景颜色没有按预期使用。我不应该为这个任务使用 isKeyWindow 吗?

- (void)drawRect:(NSRect)dirtyRect {

    if ([[self window] isKeyWindow]) {

        NSColor *startingColor = [NSColor colorWithCalibratedWhite:0.8 alpha:1.0];
        NSColor *endingColor = [NSColor colorWithCalibratedWhite:0.6 alpha:1.0];
        NSGradient* aGradient = [[NSGradient alloc]
                             initWithStartingColor:startingColor
                             endingColor:endingColor];
        [aGradient drawInRect:[self bounds] angle:270];

    } else {
        NSColor *startingColor = [NSColor colorWithCalibratedWhite:0.9 alpha:1.0];
        NSColor *endingColor = [NSColor colorWithCalibratedWhite:0.8 alpha:1.0];
        NSGradient* aGradient = [[NSGradient alloc]
                             initWithStartingColor:startingColor
                             endingColor:endingColor];
        [aGradient drawInRect:[self bounds] angle:270];
    }
    [super drawRect:dirtyRect];
}
4

1 回答 1

3

我认为您看到的行为是因为窗口不一定会在获得或失去关键状态时重新绘制。当它成为或退出密钥时,我会尝试在窗口上强制更新。就像是:

- (void) viewDidMoveToWindow
{
    if( [self window] == nil ) {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    else {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(forceUpdate)
                                                     name:NSWindowDidResignKeyNotification
                                                   object:[self window]];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(forceUpdate)
                                                     name:NSWindowDidBecomeKeyNotification
                                                   object:[self window]];
    }
}

- (void) forceUpdate
{
    [self setNeedsDisplay:YES];
}
于 2012-08-13T08:05:14.360 回答