cocoa - 如何在 NSButton 上绘制右上角圆角?

标签 cocoa nsbutton nsbezierpath

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

按钮的当前结构是:

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

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

最佳答案

解决方案:

覆盖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];

关于cocoa - 如何在 NSButton 上绘制右上角圆角?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15064207/

相关文章:

objective-c - 使用 "animation"以编程方式单击 NSPushButton

objective-c - NSBezierPath : Stroke with 2 or 3 colors

cocoa NSBezierPath - 中风。颜色与预定义颜色不同的崩溃

macos - 当图像插入一行时,NSTextField 在 NSTableView 中变得模糊

objective-c - 更改Cocoa中的collectionview按钮的图像

cocoa - 绑定(bind)和 NSButton

objective-c - 查看 NSBezierPath(s) 是否形成某种形状或图案

objective-c - cocoa 线程脾气暴躁

objective-c - NSPushOnPushOffButton 不停留 "Pushed In"

macos - 使用 NSButton 超链接预填充电子邮件内容