【问题标题】:NSShadow with a NSButton subclass带有 NSButton 子类的 NSShadow
【发布时间】:2009-12-23 13:51:47
【问题描述】:

这是我的代码:

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

【问题讨论】:

    标签: objective-c cocoa drawing subclass nsbutton


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      相关资源
      最近更新 更多