2016-12-29 32 views
11

我製作瞭如下的弧形。通過指定半徑,起始角,終止角如何爲Arc創建角落

CGContextAddArc(ctx, self.frame.size.width/2 , self.frame.size.height/2, 
self.radius, 2*M_PI, 3*M_PI/2-ToRad(angle), 0); 

現在我要讓拱的角落四捨五入。所以需要在兩端畫圈。因爲我使用的框架尺寸給常量不會工作。

enter image description here

+0

你是否圖形庫提供筆特性設置設置呢?像Windows GDI中的PS_ENDCAP_ROUND一樣。 – MBo

回答

9

嘗試圖形狀態參數CGContextSetLineJoin設置爲圓:CGContextSetLineCap(ctx, kCGLineCapRound);

這是基於你的問題我的研究。該方法駐留在drawRect:方法中,我寫了一個簡短的方法來抽象它,以便僅爲方法提供參數startAngle,endAngle和radius。當然它可以被改進。

我提供你這個方法的輸出圖片。

- (void)drawRect:(CGRect)rect { 
    float startAngle = 0; 
    float endAngle = 60; 
    float radius = 50.0; 

    CGContextRef ctx = [self drawRoundedArcWithStartAngle:startAngle endAngle:endAngle radius:radius]; 
    CGContextStrokePath(ctx); 
} 

- (CGContextRef)drawRoundedArcWithStartAngle:(float)startAngle endAngle:(float)endAngle radius:(float)radius { 

    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    // [CGContextAddArc(ctx, self.frame.size.width/2 , self.frame.size.height/2, radius, 2*M_PI, 3*M_PI/2-(angle * M_PI/180), 0)]; 

    CGContextAddArc(ctx, self.frame.size.width/ 2, self.frame.size.height/2, radius, (startAngle * M_PI/180), (endAngle * M_PI/180), 0); 
    CGContextSetRGBStrokeColor(ctx, 0.0, 0.0, 0.0, 1.0); 
    CGContextSetLineWidth(ctx, 20.0f); 
    CGContextSetLineCap(ctx, kCGLineCapRound); 
    return ctx; 
} 

希望它有幫助!

Arc with rounding. Output from the method above.

+0

它的工作正常。 – Saranjith

+0

將此答案標記爲已接受,如果它解決了您的問題@Saranjith – raki

0

您可以輕鬆地

Objective-C的

CGContextSetLineCap(context, kCGLineCapRound); 

斯威夫特

context?.setLineCap(.round) 
context?.addArc(center: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true/false) 
+0

它不起作用... – Saranjith