制作多边形曲线的锐边(顶点)

时间:2012-01-16 13:52:42

标签: iphone objective-c xcode core-graphics quartz-2d

我使用UIBezierPath绘制了一个多边形。我需要让它的顶点弯曲。我怎样才能做到这一点。我使用[path addLineToPoint:CGPointMake(xPoint,yPoint)]方法绘制线条。我试过用 [path addCurveToPoint:self.nextPoint controlPoint1:self.controlPoint controlPoint2:self.controlPoint];  但没有运气。任何帮助将不胜感激。

Polygon that needs to be made smooth

1 个答案:

答案 0 :(得分:1)

这取决于你的意图。如果您需要曲线穿过每个顶点,最好使用不同的样条曲线,例如Catmull-Rom样条曲线。它们具有通过所有曲线控制点的有用特性。 Bézier曲线没有这个属性;相反,曲线由控制点的凸包边界限定。您还应该知道,当控制点非常接近时,您将不得不使用任意高阶样条曲线来避免自相交。

如果您的控制点已经顺时针或逆时针顺序,则以下代码将评估并绘制连接点的闭合Catmull-Rom样条曲线。

#define SMOOTHNESS 20

for(NSUInteger i = 0; i <= pointCount; ++i) {
    CGPoint p0 = points[(i + 0) % pointCount];
    CGPoint p1 = points[(i + 1) % pointCount];
    CGPoint p2 = points[(i + 2) % pointCount];
    CGPoint p3 = points[(i + 3) % pointCount];

    for(CGFloat t = 0; t <= 1; t += 1.0 / SMOOTHNESS) {
        CGFloat t2 = t*t, t3 = t * t * t;
        CGFloat x = 0.5 *((2 * p1.x) + (-p0.x + p2.x) * t + (2*p0.x - 5*p1.x + 4*p2.x - p3.x) * t2 + (-p0.x + 3*p1.x- 3*p2.x + p3.x) * t3);
        CGFloat y = 0.5 *((2 * p1.y) + (-p0.y + p2.y) * t + (2*p0.y - 5*p1.y + 4*p2.y - p3.y) * t2 + (-p0.y + 3*p1.y- 3*p2.y + p3.y) * t3);

        if(i == 0 && t == 0)
            CGContextMoveToPoint(context, x, y);
        else
            CGContextAddLineToPoint(context, x, y);
    }
}

CGContextStrokePath(context);

导致:

Polygon with smoothed vertices

相关问题