C# GDI+ 實現物體橢圓運動詳解
作者:iamrick
注意事項1. 確保啟用雙緩沖以防止閃爍2. 注意釋放GDI+資源(使用using語句)3. 合理設置定時器間隔,避免過于頻繁的刷新4. 考慮性能優(yōu)化,避免在繪圖時進行復雜計算。
一、原理介紹
橢圓運動是一種常見的周期性運動,其軌跡形成一個橢圓。物體在橢圓上運動的坐標可以用以下參數方程表示:
x = a * cos(t)
y = b * sin(t)
其中:
- a 為橢圓的長半軸
- b 為橢圓的短半軸
- t 為參數角度(0-360度)
二、完整代碼實現
圖片
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(); // 觸發(fā)重繪
}
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));
}
}
}
三、注意事項
- 確保啟用雙緩沖以防止閃爍
- 注意釋放GDI+資源(使用using語句)
- 合理設置定時器間隔,避免過于頻繁的刷新
- 考慮性能優(yōu)化,避免在繪圖時進行復雜計算
這個示例展示了如何使用C# GDI+實現基本的橢圓運動效果,代碼簡潔且易于理解,可以作為更復雜動畫效果的基礎。
責任編輯:武曉燕
來源:
技術老小子