所以,我有一个矩形“rectangle1”,160,160。
我希望它能够顺利地移动到160,30,持续时间约为1秒。 (时间延迟)
我已经发现移动形状的一些基本代码是
rectangle1.Location = new Point(160,30);
然而,当我尝试使用
进行for循环时rectangle1.Location = new Point(160, rectangle1.Location.Y - 100);
它刚刚移动到那里。我本应该期待的。与相同
int count = 0;
while(count != 300)
{
rectangle1.Location = new Point(160, rectangle1.Location.Y -1);
count += 2;
}
所以,我假设我需要某种时钟/定时器循环,将其移动x pixels every x milliseconds
。不知道怎么做,所以请帮助。
另外,我将水平设置另外两个矩形,然后以与rectangle1相同的时间/速度向上移动。我想我必须“延迟”矩形1的运动直到它们就位,对吗?
感谢。
PS:我已经google了一下,但由于我不完全确定我在寻找什么,所以效果不佳。答案 0 :(得分:3)
如果你需要平稳的动作,那么使用计时器,线程,背景工作者是很棒的。
这是你需要做的。假设你有增加/减少x的代码,y指向形状。
步骤:
将计时器间隔设置为例如100
设置整数int count = 0; *
进行移动工作
private void timer1_Tick(object sender, EventArgs e)
// no need to use your while loop anymore :))
{
If(count< 300) //set to your own criteria
{
//e.g. myrect.location=new point(x,y);
// rectangle1.Location = new Point(160, rectangle1.Location.Y -1);
}
count += 2;
}
答案 1 :(得分:0)
您可以这样做:
public partial class Form1 : Form
{
private BackgroundWorker worker = null;
private Rectangle rect = new Rectangle(0, 0, 100, 100);
private Button button1 = new Button();
private TextBox textBox1 = new TextBox();
public Form1()
{
InitializeComponent();
this.SuspendLayout();
button1.Location = new System.Drawing.Point(260, 171);
button1.Name = "button1";
button1.Size = new System.Drawing.Size(75, 23);
button1.TabIndex = 0;
button1.Text = "button1";
button1.UseVisualStyleBackColor = true;
button1.Click += new System.EventHandler(button1_Click);
textBox1.Location = new System.Drawing.Point(282, 245);
textBox1.Name = "textBox1";
textBox1.Size = new System.Drawing.Size(100, 20);
textBox1.TabIndex = 1;
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button1);
this.ResumeLayout();
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
rect.Y = i;
System.Threading.Thread.Sleep(100);
worker.ReportProgress(i);
}
}
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (this.InvokeRequired)
{
Invoke(new ProgressChangedEventHandler(worker_ProgressChanged), new object[] { sender, e });
return;
}
this.Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
worker.RunWorkerAsync();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.DrawRectangle(SystemPens.ActiveBorder, rect);
}
}