使用绘画方法在表格上创建运动-不起作用

问题描述 投票:0回答:1

我正在尝试使用paint方法在表单上绘制移动的矩形和圆形。一个按钮应该开始该过程。第二次按应结束程序。一旦变量是在开始时设置为True的全局布尔值。X1是全局int,在开始时设置为10。Up是一个全局布尔值,在启动时设置为true。

每次迭代时,X1变量都会不断增加,直到100,然后逐渐减少到10。

我观察到以下两个问题。

  1. 图纸在表格上没有移动
  2. 程序一旦启动,便无法控制表格

以下为代码:

private void Form1_Paint(object sender, PaintEventArgs e)  
{  

    Pen red = new Pen(Color.Red,3);  
    Rectangle rect = new Rectangle(x1, x1, x1, x1);  
    Rectangle circle = new Rectangle(x1+10, x1 + 10, x1 + 50, x1 + 50);  

    //Graphics g = e.Graphics;  
    Graphics g = CreateGraphics();  
    g.DrawRectangle(red,rect);  
    g.DrawEllipse(red, circle);  

    red.Dispose();  
    g.Dispose();             
}  

private void button2_Click(object sender, EventArgs e)  
{            
    if (once)             
        once = false;              
    else  
        Environment.Exit(0);  

    while (true)  
    {  
        if (up )  
        {  
            x1 += 10;  
            if (x1 > 100)  
                up = false;  
        }  
        else  
        {  
            x1 -= 10;  
            if (x1 <= 10)  
                up = true;  
        }  
        this.Invalidate();  
        Thread.Sleep(500);  
    }                      
}  
c# winforms paint
1个回答
0
投票

这里是使用System.Windows.Forms.Timer完成此任务的一种方法,请参见更改和注释:

private int x1 = 4;
System.Windows.Forms.Timer timer;
private bool once = true;
private bool up = false;
private void Form1_Paint(object sender, PaintEventArgs e)
{
    // use e.Graphics
    Graphics g = e.Graphics;
    Pen red = new Pen(Color.Red, 3);
    Rectangle rect = new Rectangle(x1, x1, x1, x1);
    Rectangle circle = new Rectangle(x1 + 10, x1 + 10, x1 + 50, x1 + 50);
    g.DrawRectangle(red, rect);
    g.DrawEllipse(red, circle);

    red.Dispose();
    g.Dispose();
}

private void button2_Click(object sender, EventArgs e)
{
    if (once)
    {
        once = false;
        Init();
    }
    else
    {
        if (timer != null)
        {
            timer.Stop();
            timer.Dispose();
            timer = null;
        }
        // you can exit app...
         Application.Exit();
    }
}

private void Init()
{
    if (timer == null)
    {
        timer = new Timer();
        timer.Interval = 500;
        timer.Tick += timer_tick;
    }

    timer.Start();
}

private void timer_tick(object sender, EventArgs e)
{
    if (up)
    {
        x1 += 10;
        if (x1 > 100)
            up = false;
    }
    else
    {
        x1 -= 10;
        if (x1 <= 10)
            up = true;
    }
    this.Invalidate();
}
© www.soinside.com 2019 - 2024. All rights reserved.