编辑
2025-09-20
C#
00

目录

原理介绍
完整代码实现
注意事项

原理介绍

椭圆运动是一种常见的周期性运动,其轨迹形成一个椭圆。物体在椭圆上运动的坐标可以用以下参数方程表示:

Python
x = a * cos(t) y = b * sin(t)

其中:

  • a 为椭圆的长半轴
  • b 为椭圆的短半轴
  • t 为参数角度(0-360度)

完整代码实现

image.png

C#
public partial class Form1 : Form { private Timer timer; private double angle = 0; private const double STEP = 1; // 角度步进值 private const int A = 150; // 长半轴 private const int B = 100; // 短半轴 private Point center; // 椭圆中心点 private Point currentPos; // 运动物体当前位置 public Form1() { InitializeComponent(); // 启用双缓冲,防止闪烁 this.DoubleBuffered = true; // 设置控件样式为全部在WM_PAINT中绘制 // 这样可以防止控件擦除背景时闪烁,提高绘制效率 this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 计算中心点 center = new Point(this.ClientSize.Width / 2, this.ClientSize.Height / 2); // 初始化定时器 timer = new Timer(); timer.Interval = 20; // 20ms更新一次 timer.Tick += Timer_Tick; timer.Start(); } private void Timer_Tick(object sender, EventArgs e) { // 计算新位置 angle = (angle + STEP) % 360; double radian = angle * Math.PI / 180; currentPos = new Point( (int)(center.X + A * Math.Cos(radian)), (int)(center.Y + B * Math.Sin(radian)) ); this.Invalidate(); // 触发重绘 } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Graphics g = e.Graphics; // 设置高质量绘图 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; // 绘制椭圆轨迹 using (Pen pen = new Pen(Color.LightGray, 1)) { g.DrawEllipse(pen, center.X - A, center.Y - B, 2 * A, 2 * B); } // 绘制运动物体 using (SolidBrush brush = new SolidBrush(Color.Blue)) { const int BALL_SIZE = 20; g.FillEllipse(brush, currentPos.X - BALL_SIZE / 2, currentPos.Y - BALL_SIZE / 2, BALL_SIZE, BALL_SIZE); } // 绘制中心点 using (SolidBrush brush = new SolidBrush(Color.Red)) { g.FillEllipse(brush, center.X - 3, center.Y - 3, 6, 6); } // 显示当前角度 using (Font font = new Font("Arial", 12)) using (SolidBrush brush = new SolidBrush(Color.Black)) { g.DrawString($"Angle: {angle:F1}°", font, brush, new PointF(10, 10)); } } }

注意事项

  1. 确保启用双缓冲以防止闪烁
  2. 注意释放GDI+资源(使用using语句)
  3. 合理设置定时器间隔,避免过于频繁的刷新
  4. 考虑性能优化,避免在绘图时进行复杂计算

这个示例展示了如何使用C# GDI+实现基本的椭圆运动效果,代码简洁且易于理解,可以作为更复杂动画效果的基础。

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!