Bezier curve algorithm in objective-c

不想你离开。 提交于 2019-12-22 10:43:58

问题


Can someone smarter than me take a look at this. I'm trying to implement a Bezier curve algorithm I found here in objective-c.

The output is way wrong. I think I converted the code correctly so either the original was wrong or was not ment to be used like this... If I use the built in NSBezierPath the curve looks great but I can't use the built in NSBezierPath.

NSBezierPath example

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)];

My code trying to draw a bezier curve

- (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;
    }
}

Edit

See Bezier curve algorithm in objective-c needs a tweak for a completed functional Bezier Curve method.


回答1:


I used this Bezier function with my xy plotter and found a small error with the 'to'. The to.x to.y and b.x b.y need to be switched so that the pen starts at from and ends at 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:


It looks to me like you have the wrong coefficients with each point and that one of your adds became a multiply. I think what you want is this:

    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;


来源:https://stackoverflow.com/questions/10458596/bezier-curve-algorithm-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!