2009-05-22 23 views
4

我想創建一個應該看起來像UIButtonTypeRoundedRect的自定義UIButton。在我的drawRect中,我創建了一個路徑,第一次調用CGContextMoveToPoint(),然後四次調用CGContextAddArc()。然後我撫摸着這條路。但是,在最終的圖像中,四個圓角明顯比其餘路徑厚。我懷疑這與反鋸齒有關,所以我試着用CGContextSetShouldAntiAlias()把它關掉,但後來看起來更糟。我也嘗試過使用線條寬度,但弧線總是比直線更粗。 Apple的UIButtonTypeRoundedRect看起來非常好,所以它必須有可能以某種方式解決。有人有線索嗎?爲什麼我的石英弧顯示比直線更粗?

編輯:相關代碼:

CGContextRef context = UIGraphicsGetCurrentContext(); 
CGContextBeginPath(context); 

CGContextMoveToPoint(context, rect.origin.x + kRoundedRectButtonRadius, rect.origin.y); 
CGContextAddArc(context, rect.origin.x + rect.size.width - kRoundedRectButtonRadius, rect.origin.y + kRoundedRectButtonRadius, kRoundedRectButtonRadius, 3 * M_PI_2, 0, NO); 
CGContextAddArc(context, rect.origin.x + rect.size.width - kRoundedRectButtonRadius, rect.origin.y + rect.size.height - kRoundedRectButtonRadius, kRoundedRectButtonRadius, 0, M_PI_2, NO); 
CGContextAddArc(context, rect.origin.x + kRoundedRectButtonRadius, rect.origin.y + rect.size.height - kRoundedRectButtonRadius, kRoundedRectButtonRadius, M_PI_2, M_PI, NO); 
CGContextAddArc(context, rect.origin.x + kRoundedRectButtonRadius, rect.origin.y + kRoundedRectButtonRadius, kRoundedRectButtonRadius, M_PI, 3 * M_PI_2, NO); 

CGContextClosePath(context); 
CGContextSetLineWidth(context, 1.7); 
CGContextStrokePath(context); 
+0

也許發佈代碼可以幫助我們幫助你? – 2009-05-22 21:24:00

回答

11

我碰到的這個與繪製自定義按鈕之前。你看到的行爲源於可可的繪圖程序在你要求它們的像素位置周圍繪製線居中。讓我解釋。

您正在繪製的直線落在按鈕矩形的邊緣。當你的繪圖程序被調用時,Cocoa已經方便地將裁剪區域設置爲按鈕矩形的確切邊界,但是當你讓Cocoa沿着邊緣繪製一條線時,恰好有一半線被繪製在裁剪矩形之外。

您注意到圓角的差異,因爲彎曲部分完全落入裁剪矩形內部,因此沒有裁剪掉。

現在的解決方案:

讓我們假設你繪製的線是完全相同的兩個像素厚。這意味着一個像素被繪製在裁剪矩形內,一個被繪製在外部(因此被忽略)。你所要做的就是將你的線畫一個像素靠近矩形的中心。在自定義繪圖例程的情況下,您可能正在使用:

NSRect myBounds = [self bounds]; 

然後從那裏計算您的角點。 Insead,使用:

NSRect myProperBounds = NSInsetRect([self bounds], 1.0, 1.0); 

你應該很好走。

+0

你是一位天才,我的朋友 - 我應該永遠感激你! – eliego 2009-05-22 22:01:18

相關問題