如何在NSButton上绘制右上角?

时间:2013-02-25 09:52:49

标签: cocoa nsbutton nsbezierpath

使用CALayer或NSBezierPath可以通过多种方式在Cocoa中绘制四个圆角。但是如何在NSButton上绘制一个圆角?

按钮的当前结构是:

NSButton *button = [[NSButton alloc] initWithFrame:NSMakeRect(0, 0, 50, 20)];
[button setTitle:@"My button"];
[button.cell setBackgroundColor:[NSColor grayColor]];

我想做的是有一个圆角的右上角,半径为10.我该怎么做?

3 个答案:

答案 0 :(得分:4)

<强> SOLUTION:

覆盖drawRect:

CGFloat cornerRadius = 10;

NSBezierPath *path = [NSBezierPath bezierPath];

// Start drawing from upper left corner
[path moveToPoint:NSMakePoint(NSMinX(self.bounds), NSMinY(self.bounds))];

// Draw top border and a top-right rounded corner
NSPoint topRightCorner = NSMakePoint(NSMaxX(self.bounds), NSMinY(self.bounds));
[path lineToPoint:NSMakePoint(NSMaxX(self.bounds) - cornerRadius, NSMinY(self.bounds))];
[path curveToPoint:NSMakePoint(NSMaxX(self.bounds), NSMinY(self.bounds) + cornerRadius)
     controlPoint1:topRightCorner
     controlPoint2:topRightCorner];

// Draw right border, bottom border and left border
[path lineToPoint:NSMakePoint(NSMaxX(self.bounds), NSMaxY(self.bounds))];
[path lineToPoint:NSMakePoint(NSMinX(self.bounds), NSMaxY(self.bounds))];
[path lineToPoint:NSMakePoint(NSMinX(self.bounds), NSMinY(self.bounds))];

// Fill path
[[NSColor whiteColor] setFill];
[path fill];

答案 1 :(得分:2)

您需要使用NSBezierPath并根据您的要求绘制自定义按钮。

你需要做这样的事情:

NSBezierPath *path = [NSBezierPath bezierPath];
[path setLineWidth:1];
[path moveToPoint:NSMakePoint(0, 0)];

[path curveToPoint:NSMakePoint(width * 0.1, height)
     controlPoint1:NSMakePoint(width * 0.05, height)
     controlPoint2:NSMakePoint(width * 0.03, height * 0.05)];

等等......直到你制作一个关闭的按钮区域,你才会得到确切的形状。

答案 2 :(得分:1)

基于Christoffer Christoffer's approach,我创建了一个更通用的解决方案,您可以选择要舍入的角落。它位于Swift 3中,同时适用于macOS和amp;式IO / tvOS。

您可以在此处找到Swift游乐场:https://github.com/janheiermann/BezierPath-Corners