3

有几种方法可以在 Cocoa 中绘制四个圆角,使用 CALayer 或 NSBezierPath。但是如何在 NSButton 上绘制一个圆角?

按钮的当前结构是:

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

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

4

3 回答 3

4

解决方案:

覆盖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];
于 2013-02-26T12:02:09.050 回答
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)];

依此类推...直到您制作一个封闭的按钮区域并获得精确的形状。

于 2013-02-25T10:11:52.410 回答
2

基于 Christoffer Christoffer 的方法,我创建了一个更通用的解决方案,您可以在其中选择要圆的角。它在 Swift 3 中,也适用于 macOS 和 iOS/tvOS。

你可以在这里找到 Swift Playground:https ://github.com/janheiermann/BezierPath-Corners

于 2017-03-25T16:32:51.017 回答