这是我的代码:
- (void)drawRect:(NSRect)dirtyRect {
// Drawing code here.
// Create the Gradient
NSGradient *fillGradient = nil;
if (mouseIsDown)
fillGradient = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithCalibratedRed:0.868 green:0.873 blue:0.868 alpha:1.000] endingColor:[NSColor colorWithCalibratedRed:0.687 green:0.687 blue:0.687 alpha:1.000]];
else
fillGradient = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithCalibratedRed:0.687 green:0.687 blue:0.687 alpha:1.000] endingColor:[NSColor colorWithCalibratedRed:0.868 green:0.873 blue:0.868 alpha:1.000]];
// Add The Text
NSDictionary *att = nil;
NSMutableParagraphStyle *style =
[[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:NSLineBreakByWordWrapping];
[style setAlignment:NSLeftTextAlignment];
att = [[NSDictionary alloc] initWithObjectsAndKeys:
style, NSParagraphStyleAttributeName,
[NSColor blackColor],
NSForegroundColorAttributeName, nil];
[style release];
// Create the path
aPath = [[NSBezierPath bezierPath] retain];
[aPath moveToPoint:NSMakePoint(10.0, 0.0)];
[aPath lineToPoint:NSMakePoint(70.0, 0.0)];
[aPath lineToPoint:NSMakePoint(70.0, 23.0)];
[aPath lineToPoint:NSMakePoint(10.0, 23.0)];
[aPath lineToPoint:NSMakePoint(0.0, 10.0)];
NSShadow *shadow = [[NSShadow alloc] init];
[shadow setShadowColor:[NSColor blackColor]];
[shadow setShadowOffset:NSMakeSize(0, 0)];
[shadow setShadowBlurRadius:5];
[shadow set];
NSRect rect;
rect.size = [[self title] sizeWithAttributes:att];
rect.origin.x = floor( NSMidX([self bounds]) - rect.size.width / 2 - 8);
rect.origin.y = floor( NSMidY([self bounds]) - rect.size.height / 2 - 5);
[fillGradient drawInBezierPath:aPath angle:90.0];
[fillGradient release];
[[self title] drawInRect:rect withAttributes:att];
[att release];
} 问题是 NSShadow 在文本后面而不是 NSBezierPath,'aPath',我将如何添加 NSBezierPath 的阴影?
最佳答案
尝试包装 NSShadow 和贝塞尔路径填充内容(例如,从 aPath = [[NSBezierPath bezierPath] retain];
到 [fillGradient release];
)在 [NSGraphicsContext saveGraphicsState]
和 [NSGraphicsContext restoreGraphicsState]
。
此外,阴影可能会被 View 的边界裁剪(我不记得这是不是真的)。
(此外,“更合适”的方法可能是将 NSButtonCell
也子类化,覆盖 drawWithFrame:inView:
/-drawInteriorWithFrame: inView:
并从按钮的 +cellClass
方法返回自定义单元格类(确保也在 IB 中设置正确的单元格类,或者在按钮的 - initWithCoder:
)。不过,你这样做的方式可能会很好地满足你的需求。)
关于objective-c - 带有 NSButton 子类的 NSShadow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1950410/