2013-02-25 64 views
3

Cocoa中有四种绘制圆角的方法,使用CALayer或NSBezierPath。但是我怎样才能在NSButton上绘制一个圆角?如何在NSButton上绘制右上角的圆角?

按钮目前的结构是:

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

我想要做的是有与10半径如何做一个圆形右上角的?

+0

如果您发布的解决方案,为什么不将它张贴作为一个答案? – 2013-02-25 13:34:14

+0

好吧,它完成了...... – Christoffer 2013-02-26 12:03:04

回答

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)]; 

等等......直到你犯了一个封闭的按钮区域,你会得到精确的形状。

3

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]; 
+0

所以你解决了这个问题:) – 2013-02-26 12:55:37