ios 贝塞尔曲线轨迹更加平滑

在使用贝塞尔曲线画图的时候,在画线速度比较快的时候可能会出现不够平滑的现象,所以我们要处理一下这样的问题,首先我将代码附在下面,在这段代码之前要获得这个贝塞尔曲线上的点,在我的博客中有一篇文章就是介绍怎么获得贝塞尔曲线上的点的,代码如下:
#define POINT(_INDEX_) [(NSValue *)[points objectAtIndex:_INDEX_] CGPointValue]

@implementation UIBezierPath (Smoothing)

- (UIBezierPath *)smoothedPath:(int)granularity
{
    NSMutableArray *points = [self.points mutableCopy];
    if (points.count < 4) {
        return [self copy];
    }
    
    UIBezierPath *smoothedPath = [UIBezierPath bezierPath];
    smoothedPath.lineWidth = self.lineWidth;
    [smoothedPath moveToPoint:POINT(0)];
    [smoothedPath addLineToPoint:POINT(1)];
    for (int index = 3; index < points.count; index ++) {
        CGPoint p0 = POINT(index - 3);
        CGPoint p1 = POINT(index - 2);
        CGPoint p2 = POINT(index - 1);
        CGPoint p3 = POINT(index);
        for (int i = 1; i < granularity; i++) {
            float t = (float)i * (1.0 / granularity);
            float tt = t * t;
            float ttt = tt * t;
            
            CGPoint pi;
            pi.x = 0.5 * (2 * p1.x +(p2.x - p0.x) * t +(2 * p0.x - 5 * p1.x + 4 *p2.x - p3.x) * tt + (3 * p1.x - p0.x - 3 *p2.x + p3.x) *ttt );
            pi.y = 0.5 * (2 * p1.y +(p2.y - p0.y) * t +(2 * p0.y - 5 * p1.y + 4 *p2.y - p3.y) * tt + (3 * p1.y - p0.y - 3 *p2.y + p3.y) *ttt );
            [smoothedPath addLineToPoint:pi];
        }
        [smoothedPath addLineToPoint:p2];
    }
    [smoothedPath addLineToPoint:POINT(points.count - 1)];
    return smoothedPath;
    
}

@end
在这里采用的是Catmull-Rom插值技术实现的,其实就是一个比较特殊的贝塞尔曲线,如果想用这个方式进行插值,那么在这个曲线上最少要有4个点存在,因为这种方式只能在中间的两个点进行插值,例如有4个点分别是p0、p1、p2、p3依次在这个贝塞尔曲线上,那么我们积可以将值插到p1、p2之间,在上面的代码中可以看到变量t,t的范围是[0,1],当t=0到t=1变化,那么曲线就会从p1(t=0)到p2(t=1)运动,计算出来的点的切向量和这个点的周围两个起点和终点的切向量是平行的,那么如果想要使曲线更加的平滑,那么就要取到更多的点p0、p1、p2、p3、p4,这样就可以有两组分别是p0、p1、p2、p3和p1、p2、p3、p4,就能够在p1、p2和p2、p3之间进行插值,以此类推,使曲线更加的平滑

你可能感兴趣的:(iOS)