三阶贝塞尔曲线 C# 代码
时间: 2023-09-21 17:08:49 浏览: 126
以下是一个简单的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, 200);
controlPoints[1] = new Point(150, 100);
controlPoints[2] = new Point(250, 300);
controlPoints[3] = new Point(350, 200);
this.Paint += BezierCurveForm_Paint;
}
private void BezierCurveForm_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Pen pen = new Pen(Color.Red, 2);
// 绘制控制点
for (int i = 0; i < controlPoints.Length; i++)
{
g.FillEllipse(Brushes.Black, controlPoints[i].X - 3, controlPoints[i].Y - 3, 6, 6);
}
// 绘制贝塞尔曲线
for (float t = 0; t <= 1; t += 0.01f)
{
Point curvePoint = CalculateBezierPoint(t);
g.DrawEllipse(pen, curvePoint.X, curvePoint.Y, 1, 1);
}
}
private Point CalculateBezierPoint(float t)
{
float u = 1 - t;
float tt = t * t;
float uu = u * u;
float uuu = uu * u;
float ttt = tt * t;
Point p = new Point();
p.X = (int)(uuu * controlPoints[0].X);
p.X += (int)(3 * uu * t * controlPoints[1].X);
p.X += (int)(3 * u * tt * controlPoints[2].X);
p.X += (int)(ttt * controlPoints[3].X);
p.Y = (int)(uuu * controlPoints[0].Y);
p.Y += (int)(3 * uu * t * controlPoints[1].Y);
p.Y += (int)(3 * u * tt * controlPoints[2].Y);
p.Y += (int)(ttt * controlPoints[3].Y);
return p;
}
public static void Main()
{
Application.Run(new BezierCurveForm());
}
}
```
这段代码创建了一个窗体,并在窗体上绘制了一个三阶贝塞尔曲线。控制点用黑色圆圈表示,曲线用红色细线绘制。你可以根据需要修改控制点的位置来调整曲线的形状。
阅读全文