2013-03-05 88 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]; 
} 

希望这会有所帮助。如果您有任何问题,请随时问,祝您有美好的一天!

〜致命豪猪