Objective-C中的贝塞尔曲线算法

3

有比我更聪明的人能否看一下这个。我正在尝试在objective-c中实现我在这里找到的Bezier曲线算法。

输出结果完全错误。我认为我正确地转换了代码,所以要么原始代码有误,要么不应该像这样使用... 如果我使用内置的NSBezierPath,曲线看起来很好,但我不能使用内置的NSBezierPath

NSBezierPath示例

NSBezierPath *bezierPath = [[NSBezierPath alloc] init];
[bezierPath setLineWidth:1.0f];
[bezierPath moveToPoint:NSMakePoint(x1, y1)];
[bezierPath curveToPoint:NSMakePoint(x4, y4) controlPoint1:NSMakePoint(x2, y2) controlPoint2:NSMakePoint(x3, y3)];

我的代码试图绘制贝塞尔曲线

- (void)drawBezierFrom:(NSPoint)from to:(NSPoint)to controlA:(NSPoint)a controlB:(NSPoint)b color:(NSUInteger)color
{
    float qx, qy;
    float q1, q2, q3, q4;
    int plotx, ploty;
    float t = 0.0;
    
    while (t <= 1)
    {
        q1 = t*t*t*-1 + t*t*3 + t*-3 + 1;
        q2 = t*t*t*3 + t*t*-6 + t*3;
        q3 = t*t*t*-3 + t*t*3;
        q4 = t*t*t;
    
        qx = q1*from.x + q2*to.x * q3*a.x + q4*b.x;
        qy = q1*from.y + q2*to.y * q3*a.y + q4*b.y;
    
        plotx = round(qx);
        ploty = round(qy);

        [self drawPixelColor:color atX:plotx y:ploty];
    
        t = t + 0.003;
    }
}

编辑

请查看这篇文章,它提供了一个完整的功能性贝塞尔曲线方法。

2个回答

4

我在我的xy绘图仪中使用了这个Bezier函数,发现了一个小错误 "to"。 to.x to.yb.x b.y需要交换,以便笔从from开始,并以to结束。

qx = q1*from.x + q2*a.x + q3*b.x + q4*to.x;
qy = q1*from.y + q2*a.y + q3*b.y + q4*to.y;

2

我觉得你在每个点上使用了错误的系数,并且其中一个加号变成了乘号。我认为你想要的是这样的:

    qx = q1*from.x + q2*a.x + q3*to.x + q4*b.x;
    qy = q1*from.y + q2*a.y + q3*to.y + q4*b.y;

天啊,我盯着那个错误看了好几个小时,却没看到乘法打错了。你的代码很棒。谢谢你。 - Justin808

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接