带有NSButton子类的NSShadow

时间:2009-12-23 02:38:33

标签: objective-c cocoa drawing subclass nsbutton

这是我的代码:

- (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的阴影?

1 个答案:

答案 0 :(得分:4)

尝试在aPath = [[NSBezierPath bezierPath] retain];[fillGradient release];中包装NSShadow和bezier路径填充内容(例如,从[NSGraphicsContext saveGraphicsState][NSGraphicsContext restoreGraphicsState])。

此外,阴影可能被视图的边界剪切(我不记得这是否属实)。

(另外,执行此操作的“更合适”的方法可能是将NSButtonCell子类化,覆盖drawWithFrame:inView: / -drawInteriorWithFrame:inView:并从按钮{返回自定义单元格类{ {1}}方法(确保在IB中设置正确的单元格类,或者在按钮的+cellClass中交换它)。但是,这样做可能会很好地满足您的需求。)< / p>