objective-c - 带有 NSButton 子类的 NSShadow

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

最佳答案

尝试包装 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/

相关文章:

macos - 创建看起来像按钮的工具栏项

iphone - 迭代 NSString 数组并比较它们的更有效方法

Delphi - 自定义绘制消息列表

audio - 按频率为波形着色的代码

objective-c - 碳和 cocoa 的区别?

ios - “获取号码来源”按钮不允许输入超过两位数的号码

ios - 如何在 ios 中使用动态键对 NSMutableDictionary 进行排序?

ios - 为我的应用程序设计购物车

objective-c - 使 NSWindow(或其他东西)出现在菜单栏上方

web-applications - 在Web应用程序中交互式绘制3D数据