技术文章 > C#之B样条曲线算法(逼近算法)

C#之B样条曲线算法(逼近算法)

2018-05-26 10:14

文档管理软件,文档管理系统,知识管理系统,档案管理系统的技术资料:
B样条曲线是计算机图形学中使用较为常用的基本曲线类型。
这里先给出C#编写的B样条(B-Spline)曲线算法的最基本代码程序,供大家参考。

public class XPoint
{
public double x = 0.0;
public double y = 0.0;
}

public class Interplation_BSpline
{
/// <summary>
/// B样条曲线(逼近曲线,由四个控制点确定)
/// </summary>
/// <param name=“p1“>控制点1</param>
/// <param name=“p2“>控制点2</param>
/// <param name=“p3“>控制点3</param>
/// <param name=“p4“>控制点4</param>
/// <param name=“divisions“>分割为短直线段的数量</param>
/// <returns></returns>
public XPoint[] Execute(XPoint p1, XPoint p2, XPoint p3, XPoint p4, int divisions)
{
// 计算4x4矩阵系数
double[] a = new double[4];
double[] b = new double[4];
a[0] = (-p1.x + 3 * p2.x - 3 * p3.x + p4.x) / 6.0;
a[1] = (3 * p1.x - 6 * p2.x + 3 * p3.x) / 6.0;
a[2] = (-3 * p1.x + 3 * p3.x) / 6.0;
a[3] = (p1.x + 4 * p2.x + p3.x) / 6.0;
b[0] = (-p1.y + 3 * p2.y - 3 * p3.y + p4.y) / 6.0;
b[1] = (3 * p1.y - 6 * p2.y + 3 * p3.y) / 6.0;
b[2] = (-3 * p1.y + 3 * p3.y) / 6.0;
b[3] = (p1.y + 4 * p2.y + p3.y) / 6.0;

XPoint[] splinexy = new XPoint[divisions * 4];
splinexy[0].x = a[3];
splinexy[0].y = b[3];
// 计算参数步长
double alpha = 0.0;
double delta = 1.0 / System.Convert.ToDouble(divisions);
for (int i = 1; i <= divisions - 1; i++)
{
splinexy[i].x = (a[2] + alpha * (a[1] + alpha * a[0])) * alpha + a[3];
splinexy[i].y = (b[2] + alpha * (b[1] + alpha * b[0])) * alpha + b[3];
alpha += delta;
}
return splinexy;
}
}