获取贝塞尔曲线上的100个点

#include <stdio.h>


typedef struct

{

    float x;

    float y;

}Point2D;


void ComputeBezier (Point2D *cp, int numberOfPoints, Point2D *curve);


int main(int argc, const char * argv[])

{

    Point2D cp[] = {{10,100},{30,20},{120,20},{200,100}};

    int number = 100;

    Point2D curve[number];

    

    ComputeBezier(cp, number, curve); //因为是数组,所以不用加星号。

    

    for (int i=0; i<number; i++) {

        printf("curve[%d].x=%f,curve[%d].y=%f\n",i,curve[i].x,i,curve[i].y);

    }

    

    return 0;

}


Point2D PointOnCubicBezier (Point2D *cp, float t)

{

    float ax, bx, cx;

    float ay, by, cy;

    float tSquared, tCubed;

    Point2D result;

    

    /*計算多項式係數*/

    

    cx = 3.0 * (cp[1].x - cp[0].x);

    bx = 3.0 * (cp[2].x - cp[1].x) - cx;

    ax = cp[3].x - cp[0].x - cx - bx;

    

    cy = 3.0 * (cp[1].y - cp[0].y);

    by = 3.0 * (cp[2].y - cp[1].y) - cy;

    ay = cp[3].y - cp[0].y - cy - by;

    

    /*計算位於參數值t的曲線點*/

    

    tSquared = t * t;

    tCubed = tSquared * t;

    

    result.x = (ax * tCubed) + (bx * tSquared) + (cx * t) + cp[0].x;

    result.y = (ay * tCubed) + (by * tSquared) + (cy * t) + cp[0].y;

    

    return result;

}


void ComputeBezier (Point2D *cp, int numberOfPoints, Point2D *curve)

{

    float   dt;

    int     i;

    

    dt = 1.0 / ( numberOfPoints - 1 );

    

    for( i = 0; i < numberOfPoints; i++)

        curve[i] = PointOnCubicBezier( cp, i*dt );

}


新建一个c工程可以直接运行。



你可能感兴趣的:(c,float)