我有一个算法在Canvas上进行动画绘制,但我无法控制动画的速度,它绘制得非常快。因此,我添加了Thread.Sleep(1),但当绘制数千个像素时,这就太慢了。我尝试了一个Storyboard方法,但那也很慢。那么,有没有替代Thread.sleep来减缓循环的速度的方法呢?
void DrawGasket(object sender, DoWorkEventArgs e)
{
Random rnd = new Random();
Color color = Colors.White;
while (Counter <= noOfPx)
{
switch (rnd.Next(3))
{
case 0:
m_lastPoint.X = (m_top.X + m_lastPoint.X)/2;
m_lastPoint.Y = (m_top.Y + m_lastPoint.Y)/2;
color = Colors.White;
break;
case 1:
m_lastPoint.X = (m_left.X + m_lastPoint.X)/2;
m_lastPoint.Y = (m_left.Y + m_lastPoint.Y)/2;
color = Colors.Orange;
break;
case 2:
m_lastPoint.X = (m_right.X + m_lastPoint.X)/2;
m_lastPoint.Y = (m_right.Y + m_lastPoint.Y)/2;
color = Colors.Purple;
break;
}
Dispatcher.BeginInvoke(() =>
{
var px = new Rectangle {
Height = m_pxSize,
Width = m_pxSize,
Fill = new SolidColorBrush(color)
};
Canvas.SetTop(px, m_lastPoint.Y);
Canvas.SetLeft(px, m_lastPoint.X);
can.Children.Add(px);
lblCounter.Text = Counter.ToString();
});
Counter++;
Thread.Sleep(1);
}
}