使用 Paul de Casteljau 算法在 Objective C 中创建贝塞尔曲线

Create Bezier Curve in Objective C using Paul de Casteljau algorithm

我正在尝试使用 Paul de Casteljau 算法绘制贝塞尔曲线作为我的作业,但似乎并不完美,这里是代码

- (void)recursive_bezier :(double)x1 :(double)y1
                         :(double)x2 :(double)y2
                         :(double)x3 :(double)y3
                         :(double)x4 :(double)y4
{

  count = count+1;
  // Calculate all the mid-points of the line segments
  //----------------------
  double x12   = (x1 + x2) / 2;
  double y12   = (y1 + y2) / 2;
  double x23   = (x2 + x3) / 2;
  double y23   = (y2 + y3) / 2;
  double x34   = (x3 + x4) / 2;
  double y34   = (y3 + y4) / 2;
  double x123  = (x12 + x23) / 2;
  double y123  = (y12 + y23) / 2;
  double x234  = (x23 + x34) / 2;
  double y234  = (y23 + y34) / 2;
  double x1234 = (x123 + x234) / 2;
  double y1234 = (y123 + y234) / 2;
  
  
  if(isFlat)
  {
    //    // Draw and stop
    //    //----------------------
    [self drawLine:x1 :y1 :x4 :y4];
    
  }
  else
  {
    // Continue subdivision
    //----------------------
    if (count == 5) {
      isFlat=true;
    }

    [self recursive_bezier:x1 :y1 :x12 :y12 :x123 :y123 :x1234 :y1234];
    [self recursive_bezier:x1234 :y1234 :x234 :y234 :x34 :y34 :x4 :y4];
    
    
  }
}

- (void)drawLine :(double)x1 :(double)y1
                 :(double)x4 :(double)y4{
  countDraw = countDraw+1;
  NSLog(@"============%d============",countDraw);
  NSLog(@"x1 = %f y1 = %f",x1, y1);
  NSLog(@"x4 = %f y4 = %f",x4, y4);
   
  UIBezierPath *path = [UIBezierPath bezierPath];
  [path moveToPoint:CGPointMake(x1, y1)];
  
  [path addLineToPoint:CGPointMake(x4, y4)];
  
  CAShapeLayer *shapeLayer = [CAShapeLayer layer];
  shapeLayer.path = [path CGPath];
  shapeLayer.strokeColor = [[UIColor blueColor] CGColor];
  shapeLayer.lineWidth = 2.0;
  shapeLayer.fillColor = [[UIColor clearColor] CGColor];
  
  [self.view.layer addSublayer:shapeLayer];

}

谁能帮我解释为什么右边没有计算出来,如何使曲线平滑?

ps : 我在 Bezier Curve Algorithm

上得到了算法

问题是,一旦 isFlat 设置为 true,任何进一步的段都不会被正确细分,即使在顶层也是如此。这是因为它是与递归调用的特定级别相关的信息,而不是整个事物的全局信息。如果你逐步执行代码,这应该会更清楚。

更好的方法是将count声明为recursive_bezier的int参数,调用时在顶层传递0,调用时传递count + 1递归调用它。您可以去掉 isFlat 变量,只测试 count >= 5.