2012-05-11 120 views
4

我想複製默認的iPad的日曆事件標記,它看起來像這樣圓角的矩形:繪圖核心顯卡

enter image description here 我試圖用這個CoreGraphics中,畫一個圓角的矩形的路徑。這是結果我能想出:

enter image description here

正如你所看到的,iPad的版本看起來圓角更平滑。我試圖用一個更大的線寬,它看起來像這樣: enter image description here

我的代碼看起來像這樣(從本網站得到它):

UIColor* fillColor= [self.color colorByMultiplyingByRed:1 green:1 blue:1 alpha:0.2]; 

CGContextSetLineWidth(ctx, 1.0); 
CGContextSetStrokeColorWithColor(ctx, self.color.CGColor); 
CGContextSetFillColorWithColor(ctx, fillColor.CGColor); 

CGRect rrect = self.bounds; 

CGFloat radius = 30.0; 
CGFloat width = CGRectGetWidth(rrect); 
CGFloat height = CGRectGetHeight(rrect); 

if (radius > width/2.0) 
    radius = width/2.0; 

if (radius > height/2.0) 
    radius = height/2.0;  

CGFloat minx = CGRectGetMinX(rrect); 
CGFloat midx = CGRectGetMidX(rrect); 
CGFloat maxx = CGRectGetMaxX(rrect); 
CGFloat miny = CGRectGetMinY(rrect); 
CGFloat midy = CGRectGetMidY(rrect); 
CGFloat maxy = CGRectGetMaxY(rrect); 
CGContextMoveToPoint(ctx, minx, midy); 
CGContextAddArcToPoint(ctx, minx, miny, midx, miny, radius); 
CGContextAddArcToPoint(ctx, maxx, miny, maxx, midy, radius); 

CGContextAddArcToPoint(ctx, maxx, maxy, midx, maxy, radius); 
CGContextAddArcToPoint(ctx, minx, maxy, minx, midy, radius); 
CGContextClosePath(ctx); 
CGContextDrawPath(ctx, kCGPathFillStroke); 

// draw circle on left side 

CGRect target= CGRectMake(rect.origin.x + 4.0, 
          rect.origin.y + 3.0, 
          7.0, 7.0); 

CGContextSetFillColorWithColor(ctx, self.color.CGColor); 
CGContextSetAlpha(ctx, 0.4); 
CGContextFillEllipseInRect(ctx, target); 

CGContextSetAlpha(ctx, 0.9); 
CGContextSetStrokeColorWithColor(ctx, self.color.CGColor); 
CGContextStrokeEllipseInRect(ctx, target); 

誰能幫助我帶來的結果更接近原本的?我是否應該使用不同的技術來繪製圓角矩形,或者是否有任何參數可以更改以使其看起來更平滑? 我已經嘗試過使用UIBezierPath,但它基本上看起來一樣。有小費嗎?

[編輯] CGRectInset基於解決方案是這樣的:

enter image description here

回答

7

你的問題是,在應用筆觸上的路徑和它的一半的中心被裁剪/蒙面邊界你的看法,因爲它超出了你的看法。如果你在每個方向插入你的繪圖點,你將得到你正在尋找的結果。如果增加筆畫的寬度,則需要進一步插入繪圖(按筆畫寬度的一半(即4分寬度筆畫應插入2分)。

這可以很容易地通過更改

CGRect rrect = self.bounds; 

// Inset x and y by half the stroke width (1 point for 2 point stroke) 
CGRect rrect = CGRectInset(self.bounds, 1, 1); 
+0

感謝您的代碼,添加上面的結果。我認爲這種解決方案會導致病態。仍然要玩的顏色,但我喜歡現在的樣子:) – user826955

0

這是因爲行程的路徑,這意味着它的一半是你的矩形內,另一半超出中間位置。

要解決此問題,請在撫摸之前加倍筆劃寬度和clip to the path。結果是一個內部筆畫,它將完全位於矩形內。

請注意,剪切到Quartz中的當前路徑將重置當前路徑,因此您應該create the path as a CGPath,以便您可以add it,剪切到它,再次添加它並對其進行描邊。