3

这是我的代码:

- (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 中添加阴影?

4

1 回答 1

4

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

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

(此外,执行此操作的“更正确”的方法可能也是子类化NSButtonCell,覆盖 drawWithFrame:inView:/-drawInteriorWithFrame:inView:并从按钮的方法返回您的自定义单元格类+cellClass(确保也在 IB 中设置正确的单元格类,或将其换出在您的按钮中-initWithCoder:)。不过,您这样做的方式可能会很好地满足您的需求。)

于 2009-12-23T05:51:47.250 回答