Cocoa 如何在按钮上绘制右上角的圆角?

Cocoa 如何在按钮上绘制右上角的圆角?,cocoa,nsbutton,nsbezierpath,Cocoa,Nsbutton,Nsbezierpath,有几种方法可以在Cocoa中绘制四个圆角,可以使用CALayer或NSBezierPath。但是我怎么能在按钮上画一个圆角呢 按钮的当前结构为: NSButton *button = [[NSButton alloc] initWithFrame:NSMakeRect(0, 0, 50, 20)]; [button setTitle:@"My button"]; [button.cell setBackgroundColor:[NSColor grayColor]]; 我想做的是有一个圆角的右

有几种方法可以在Cocoa中绘制四个圆角,可以使用CALayer或NSBezierPath。但是我怎么能在按钮上画一个圆角呢

按钮的当前结构为:

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

我想做的是有一个圆角的右上角,半径为10。如何操作?

您需要使用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)];

等等。。。直到您创建一个闭合的按钮区域并获得精确的形状。

解决方案:

覆盖
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];
基于Christoffee,我创建了一个更通用的解决方案,您可以选择要绕过哪个拐角。它在Swift 3中,也适用于macOS和iOS/tvOS


您可以在此处找到Swift Playerd:

如果您发布了解决方案,为什么不将其作为答案发布?尝试在mac项目上使用此代码,但不幸的是,它不起作用!!!,圆角不正确,即BezierPath。init(rect:rect,roundedCorners:[.topLeft,.bottomRight],cornerRadius:8.0)看起来完全不符合预期。此项目使用的控制点错误,这就是为什么角不是圆的。该项目使用的是曲线(to:…)而不是附加圆弧(withCenter:…)。这就是为什么它不是你所期望的。