2013-03-05 89 views
0

我想繪製不同面的多邊形(4-12)。繪製多邊形的邏輯是什麼?對於例如如果用戶選擇6邊,它應該繪製一個六邊形,如果用戶輸入8邊,它應該繪製一個八邊形。我發現了下面的代碼,但我也想調整其中我繪製一個多邊形的UIView,以便視圖內部的形狀也隨着視圖一起增長。任何機構都可以幫助我。以下是我目前正在使用的代碼,但當我調整視圖的形狀移動到視圖中的另一個位置時,它的位置也不在中心。如何使用UIBezierPath在可可觸摸中繪製多邊形

int radius = MINIMUM(widht, height)*0.4 ; 

    for (int i = 0; i < _numberOFsides; i++){ 

      CGPoint point = CGPointMake(widht/2+radius *cosf(i*2*M_PI/_numberOFsides), widht/2+radius*sinf(i*2*M_PI/_numberOFsides)); 

      if (i==0) { 

       [_shapePath moveToPoint:point]; 

      } 
      else{ 
       [_shapePath addLineToPoint:point]; 

       [_shapePath stroke]; 
      } 

     } 
+0

你寫上面的代碼中的UIView的drawRect?並根據uiview?rect的更新高度寬度調用setneedsdisplay每次調整大小視圖。 – BhushanVU 2013-03-05 09:14:52

+0

是的。我正在寫UIView的drawrect,每次調用setneedsdisplay。我不知道邏輯有什麼問題。 – 2013-03-05 09:24:53

+0

爲什麼不嘗試先傳遞靜態值,然後嘗試通過像UIBezierPath * aPath = [UIBezierPath bezierPath]這樣的基本方式來設置ur for循環邏輯; //設置形狀的起點。 [aPath moveToPoint:CGPointMake(100.0,0.0)]; //畫出線條。 [aPath addLineToPoint:CGPointMake(200.0,40.0)]; [aPath addLineToPoint:CGPointMake(160,140)]; [aPath addLineToPoint:CGPointMake(40.0,140)]; [aPath addLineToPoint:CGPointMake(0.0,40.0)]; [aPath closePath]; – BhushanVU 2013-03-05 09:28:50

回答

1

現在調整烏爾UIBazierPath您可以添加以下代碼,

CGRect bazierRect = CGPathGetBoundingBox(bezierpath.CGPath) 
CGFloat scaleX = view.frame.size.width/bazierRect.frame.size.width; 
CGFloat scaleY = view.frame.size.height/bazierRect.frame.size.height; 
CGAffineTransform transform = CGAffineTransformMakeScale(scaleX, scaleY); 
CGPathRef newPath = CGPathCreateCopyByTransformingPath(bezierpath.CGPath, &transform); 
bezierPath.CGPath = newPath; 
CFRelease(newPath); 
0

如果你想與任何邊數的正多邊形下面的代碼會給你每條邊的頂點,很容易重新調整尺寸和邊數:

int n = 10; //number of edges 
float j = 20; //length of each edge 
float x = 130; 
float y = 250;//the point 130,250 will be at the bottom of the figure 
float angle = 2*M_PI; 
for (int i = 0; i < n; i++) { 

    CGRect frame = CGRectMake(x, y, 2, 2);//put a dot on x,y 
    NSLog(@"%f | %f, %f", angle, x, y); 
    x = x + j*cosf(angle); 
    y = y + j*sinf(angle); //move to the next point 
    angle = angle - 2*M_PI/n; //update the angle 

    //display the dot 
    UIView *rect = [[UIView alloc] initWithFrame:frame]; 
    rect.backgroundColor = [UIColor blueColor]; 
    [self.view addSubview:rect]; 
} 

希望這會有所幫助。如果您有任何問題,請隨時問,祝您有美好的一天!

〜致命豪豬