三阶贝塞尔曲线 C# 代码
时间: 2023-09-21 15:08:49 浏览: 174
c# c++ 贝塞尔曲线, 只有几行代码就可以实现,非常简单,可以在游戏中使用
以下是一个简单的三阶贝塞尔曲线的 C# 代码示例:
```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
public class BezierCurveForm : Form
{
private Point[] controlPoints;
public BezierCurveForm()
{
controlPoints = new Point[4];
controlPoints[0] = new Point(50, 100);
controlPoints[1] = new Point(150, 50);
controlPoints[2] = new Point(250, 150);
controlPoints[3] = new Point(350, 100);
this.ClientSize = new Size(400, 200);
this.Paint += new PaintEventHandler(BezierCurveForm_Paint);
}
private void BezierCurveForm_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Pen pen = new Pen(Color.Black, 2);
// 绘制控制点
for (int i = 0; i < controlPoints.Length; i++)
{
g.FillEllipse(Brushes.Red, controlPoints[i].X - 3, controlPoints[i].Y - 3, 6, 6);
}
// 绘制贝塞尔曲线
for (double t = 0; t <= 1; t += 0.01)
{
Point p = CalculateBezierPoint(t, controlPoints);
g.FillEllipse(Brushes.Blue, p.X - 1, p.Y - 1, 2, 2);
}
// 绘制控制线
g.DrawLine(pen, controlPoints[0], controlPoints[1]);
g.DrawLine(pen, controlPoints[1], controlPoints[2]);
g.DrawLine(pen, controlPoints[2], controlPoints[3]);
}
private Point CalculateBezierPoint(double t, Point[] controlPoints)
{
double u = 1 - t;
double tt = t * t;
double uu = u * u;
double uuu = uu * u;
double ttt = tt * t;
double x = uuu * controlPoints[0].X; // (1-t)^3 * P0
x += 3 * uu * t * controlPoints[1].X; // 3 * (1-t)^2 * t * P1
x += 3 * u * tt * controlPoints[2].X; // 3 * (1-t) * t^2 * P2
x += ttt * controlPoints[3].X; // t^3 * P3
double y = uuu * controlPoints[0].Y; // (1-t)^3 * P0
y += 3 * uu * t * controlPoints[1].Y; // 3 * (1-t)^2 * t * P1
y += 3 * u * tt * controlPoints[2].Y; // 3 * (1-t) * t^2 * P2
y += ttt * controlPoints[3].Y; // t^3 * P3
return new Point((int)Math.Round(x), (int)Math.Round(y));
}
public static void Main()
{
Application.Run(new BezierCurveForm());
}
}
```
这段代码创建了一个简单的窗体应用程序,绘制了一个三阶贝塞尔曲线,并显示了控制点和控制线。你可以根据需要修改控制点的坐标,以获得不同形状的贝塞尔曲线。运行程序后,你会看到绘制的贝塞尔曲线在窗体中显示出来。
阅读全文