2013-02-12 68 views
0

如何添加在圓形路徑16點,當用戶選擇一個位置x,y和點應在相等的距離,畫出圓形路徑16點與CGContextRef

所以當用戶在視圖中打了一個位置,我將完成圓圈16點, 見附件。

enter image description here

的圖像從該代碼使用:

CGPoint CenterPoint = CGPointMake(self.frame.size.width/2, self.frame.size.height/2); 
CGPoint Point; 
float Angel = 360/16; 

for (int i = 0 ; i < 16;i++) 
{ 
    float distance = [self distanceFrom:newPoint to:centerPoint]; 
    Point.x = CenterPoint.x + distance * cos(Angel); 
    Point.y = CenterPoint.y + distance * sin(Angel); 

    CGContextMoveToPoint(cacheContext, Point.x, Point.y); 
    CGContextAddLineToPoint(cacheContext, Point.x, Point.y); 
    CGContextStrokePath(cacheContext); 

    Angel+= 10; 
} 
+1

我懷疑三角參與... – trojanfoe 2013-02-12 08:11:36

+2

是,TRIG參與。採取聽我說http://www.mathsisfun.com/polar-cartesian-coordinates.html你知道半徑(一旦你選擇了一箇中心點,你知道的角度。你只需要移動圍繞所述圓極地轉換到 – Fogmeister 2013-02-12 08:12:55

+2

直角座標系僅供參考:*天使*是天體DO-古德(通常有翅膀和光環)和*角*是兩條相交線之間的空間 – dreamlax 2013-02-12 10:08:14

回答

0

檢查下面的代碼,它可以幫助你少

int startAngle = 0; 

while (startAngle < 360) 
{ 
    CAShapeLayer *slice = [CAShapeLayer layer]; 
    slice.fillColor = _buttonColor.CGColor; 
    slice.strokeColor = [UIColor clearColor].CGColor; 
    slice.lineWidth = 3.0; 

    CGFloat angle = DEGREES_TO_RADIANS(-60.0); 
    CGPoint center = CGPointMake(self.frame.size.width/2.0, self.frame.size.height/2.0); 
    CGFloat radius = self.frame.size.width/2.0; 

    UIBezierPath *piePath = [UIBezierPath bezierPath]; 
    [piePath moveToPoint:center]; 

    //[piePath addLineToPoint:CGPointMake(center.x + radius * cosf(DEGREES_TO_RADIANS(startAngle)), center.y + radius * sinf(DEGREES_TO_RADIANS(startAngle)))]; 

    [piePath addArcWithCenter:center radius:radius startAngle:DEGREES_TO_RADIANS(startAngle) endAngle:DEGREES_TO_RADIANS(startAngle + 63) clockwise:YES]; 

    // [piePath addLineToPoint:center]; 
    [piePath closePath]; // this will automatically add a straight line to the center 
    slice.path = piePath.CGPath; 

    startAngle += (360/15); 

    [self.layer addSublayer:slice]; 
} 
+0

感謝這個答案,但由此得出一個完整的圓不行。只有點。 – Aziz 2013-02-12 08:49:20

+0

你有僅繪製點或必須連接這些點也? – Exploring 2013-02-13 05:36:20

+0

沒有,只是圓點無需連接這些點,但我已經成功地終於做到這一點,我今天會發布很多的答案,謝謝尋求幫助。 – Aziz 2013-02-13 08:53:08

0

cossin功能期望在角弧度而不是度(你正在提供)。改爲嘗試這種替代方法。

float distance = [self distanceFrom:newPoint to:centerPoint]; 
CGContextSaveGState(cacheContext); 
CGContextTranslateCTM(cacheContext, CenterPoint.x, CenterPoint.y); 

for (int i = 0 ; i < 16;i++) 
{ 
    float angle = i * (M_2_PI/16); 
    CGPoint pt = CGPointMake(distance * cos(angle), distance * sin(angle)); 

    CGContextMoveToPoint(cacheContext, 0, 0); 
    CGContextAddLineToPoint(cacheContext, pt.x, pt.y); 
    CGContextStrokePath(cacheContext); 
} 
CGContextRestoreGState(cacheContext); 

這種方法轉換的背景下,這樣的原點(a.k.a中心點)真的是CenterPoint,所以你不必擔心增加CenterPoint任何東西。由於distance不受循環內任何東西,它應該被移出,使其不被不必要地重新計算。