views:

163

answers:

1

Here's My Code:

- (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];

} The problem is that the NSShadow is behind the text not the NSBezierPath, 'aPath', how would I add the shadow the the NSBezierPath?

+3  A: 

Try wrapping the NSShadow and bezier path fill stuff (e.g., from aPath = [[NSBezierPath bezierPath] retain]; to [fillGradient release];) in [NSGraphicsContext saveGraphicsState] and [NSGraphicsContext restoreGraphicsState].

Also, the shadow may be clipped by the view's bounds (I don't remember if this is true or not).

(Additionally, the "more proper" way to do this would probably be to subclass NSButtonCell as well, overriding drawWithFrame:inView:/-drawInteriorWithFrame:inView: and returning your custom cell class from your button's +cellClass method (making sure to set the proper cell class in IB as well, or swapping it out in your button's -initWithCoder:). The way you're doing it may meet your needs fine, though.)

Wevah