2013-02-25 69 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