How do I implement a Bézier curve in C++?

Recently I ran across the same question and wanted to implemented it on my own.
This image from Wikipedia helped me:

http://upload.wikimedia.org/wikipedia/commons/3/35/Bezier_quadratic_anim.gif

The following code is written in C++ and shows how to compute a quadratic bezier.

int getPt( int n1 , int n2 , float perc )
{
    int diff = n2 - n1;

    return n1 + ( diff * perc );
}    

for( float i = 0 ; i < 1 ; i += 0.01 )
{
    // The Green Line
    xa = getPt( x1 , x2 , i );
    ya = getPt( y1 , y2 , i );
    xb = getPt( x2 , x3 , i );
    yb = getPt( y2 , y3 , i );

    // The Black Dot
    x = getPt( xa , xb , i );
    y = getPt( ya , yb , i );

    drawPixel( x , y , COLOR_RED );
}

With (x1|y1), (x2|y2) and (x3|y3) being P0, P1 and P2 in the image. Just for showing the basic idea…

For the ones who ask for the cubic bezier, it just works analogue (also from Wikipedia):

http://upload.wikimedia.org/wikipedia/commons/a/a3/Bezier_cubic_anim.gif

This answer provides Code for it.

Leave a Comment