正如其他人所说,我会使用位图而不是图标。这是我的做法:
首先,创建一个包含位图的类和一个委托,该委托将指向一个方法,该方法将获取位图的位置作为时间的函数。
delegate Point PositionFunction(int time);
class MovingBitmap
{
private Bitmap bitmap;
private PositionFunction positionFunction;
public MovingBitmap(Bitmap bitmap, PositionFunction positionFunction)
{
if (bitmap == null)
{
throw new ArgumentNullException("bitmap");
}
else if (positionFunction == null)
{
throw new ArgumentNullException("bitmap");
}
this.bitmap = bitmap;
this.positionFunction = positionFunction;
}
public Bitmap Bitmap
{
get { return this.bitmap; }
}
public PositionFunction PositionFunction
{
get { return this.positionFunction; }
}
}
对于位置功能,您需要决定位图的移动方式。(注意:时间以毫秒为单位。)它可以很简单:
private Point SimpleTimeFunction(int time)
{
return new Point(time / 5, time / 5);
}
private Point ParabolaFunction(int time)
{
return new Point(time / 5, (time / 5) * (time / 5));
}
或者它可以是由多个方程组成的分段函数,例如:
if (time < 5000)
{
return new Point(time / 5, 2 * (time / 5));
}
else
{
return new Point(time / 5, time / 5) * time);
}
这一切都取决于您希望它如何移动。希望你喜欢数学。:)
然后,在将保存位图的控件中,添加一个List<MovingBitmap>
字段。
private List<MovingBitmap> bitmaps = new List<MovingBitmap>();
然后你需要一个父控件大小的位图来用作缓冲区,这样用户体验就不会闪烁。您将在缓冲区上绘制所有移动位图,然后依次在OnPaint
.
private int startTime; // set this to System.Environment.TickCount when you start
// Add this line to the constructor
this.UpdateBufferSize();
private void UpdateBufferSize()
{
if (this.buffer != null)
{
this.buffer.Dispose();
}
this.buffer = new Bitmap(this.ClientSize.Width, this.ClientSize.Height);
}
private void RefreshBuffer()
{
int timeElapsed = Environment.TickCount - this.startTime;
using (Graphics g = Graphics.FromImage(this.buffer))
{
g.Clear(this.BackColor);
foreach (MovingBitmap movingBitmap in this.bitmaps)
{
Rectangle destRectangle = new Rectangle(
movingBitmap.PositionFunction(timeElapsed),
movingBitmap.Bitmap.Size);
g.DrawImage(movingBitmap.Bitmap, destRectangle);
}
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.DrawImage(this.buffer, Point.Empty);
}
要实现动画效果,您将需要一个计时器。当计时器经过时,刷新缓冲区,然后刷新控件。
private System.Timers.Timer timer;
private ParameterlessVoid refreshMethod;
private delegate void ParameterlessVoid();
// Add these four lines to the constructor
this.timer = new System.Timers.Timer(1000 / 20); // 20 times per second
this.timer.AutoReset = true;
this.timer.Elapsed += this.HandleTimerElapsed;
this.refreshMethod = new ParameterlessVoid(this.Refresh);
private void HandleTimerElapsed(object sender, EventArgs e)
{
this.RefreshBuffer();
this.Invoke(this.refreshMethod);
}
private void Start()
{
this.startTime = System.Environment.TickCount;
this.timer.Start();
}
我认为这基本上就是你需要做的。它没有经过全面测试和调试,但它应该为您指明正确的方向。