我正在尝试使用Paul de Casteljau算法为我的作业绘制Bezier曲线,但它似乎并不完美,这里是代码
- (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];
}
任何人都可以帮助我为什么没有计算右侧以及如何使曲线平滑?
上得到了算法答案 0 :(得分:4)
问题是,一旦isFlat
设置为true,任何其他细分都不会被正确细分,即使在顶级也是如此。这是因为它是与递归调用的特定级别相关的信息,而不是整个事物的全局信息。如果您单步执行代码,则应该更清楚。
更好的方法是将count
声明为recursive_bezier
的int参数,并在调用时在顶级传递0,并在调用时传递count + 1
递归。您可以删除isFlat
变量,只测试count >= 5
。