我正在尝试使用渐变填充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];
}
答案 0 :(得分: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];
}