use*_*197 0 c# label panel button winforms
我有一个任务是使用C#在Winforms中的一个面板周围移动一个元素(Button,Label ...).
我解决了这个问题,它有效:
private void button1_Click(object sender, EventArgs e)
{
// System.Threading.Thread.Sleep(100 - auto.Geschwindigkeit);
for (int i = 0; i < panel1.Width; i++)
{
label1.Location = new Point(i, label1.Location.Y);
label2.Location = new Point(i, label2.Location.Y);
System.Threading.Thread.Sleep(50);//speed
Application.DoEvents();
}
}
Run Code Online (Sandbox Code Playgroud)
但是有没有另外一种方法可以做到这一点,例如当我想要编程游戏并且我有10个标签(代表一辆驾驶汽车)时,我认为这将超载到使用Threads,因为CPU越来越高?!"System.Threading.Thread.Sleep(50);" 将是一个元素的速度,我想我需要一些更高效的东西?!
谢谢
不要Thread.Sleep用于计时.改为使用计时器:
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Interval = 100; // animation speed
timer1.Enabled = true; // starting animation
}
private void timer1_Tick(object sender, EventArgs e)
{
// do the replacements here
}
Run Code Online (Sandbox Code Playgroud)
但说实话,我不会使用控件来表示动画对象.他们拥有您不需要的一百万个属性,事件和其他数据.相反,我会使用专用的Car对象和自定义绘图.
public class Car
{
public Size Size { get; set; }
public Color Color { get; set; }
public Point Location { get; set; }
public int Speed { get; set; }
// and whatever you need, eg. direction, etc.
}
private List<Car> cars;
public Form1()
{
InitializeComponent();
cars = new List<Car>
{
new Car { Size = new Size(30, 15), Color = Color.Blue, Location = new Point(100, 100), Speed = 1 },
new Car { Size = new Size(50, 20), Color = Color.Red, Location = new Point(200, 150), Speed = 3 },
};
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Interval = 100; // animation speed
timer1.Enabled = true; // starting animation
}
private void timer1_Tick(object sender, EventArgs e)
{
foreach (Car car in cars)
RecalculateLocation(car); // update Location by speed here
panel1.Invalidate();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
// now we are just drawing colored rectangles but you can draw car.Image or anything you want
foreach (Car car in cars)
{
using (Brush brush = new SolidBrush(car.Color))
{
e.Graphics.FillRectangle(brush, new Rectangle(car.Location, car.Size));
}
}
}
Run Code Online (Sandbox Code Playgroud)