跳过填充椭圆(c#)

本文关键字:填充 | 更新日期: 2023-09-27 18:14:44

protected override void OnPaint(PaintEventArgs e)
{
    Graphics g = e.Graphics;
    SolidBrush brush = new SolidBrush(Color.Black);
    g.FillRectangle(brush, 35, 30, 140, 420);
    if (figure.Equals("red"))
    {                
        brush.Color = Color.Red;
        g.FillEllipse(brush, 35, 30, 140, 140);
        figure = "red";
    }
    else if (figure.Equals("yellow"))
    {               
        brush.Color = Color.Yellow;
        g.FillEllipse(brush, 35, 170, 140, 140);
        figure = "yellow";
    }
    else if (figure.Equals("green"))
    {              
        brush.Color = Color.ForestGreen;
        g.FillEllipse(brush, 35, 310, 140, 140);
        figure = "green";               
    }
}

private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
    if (figure.Equals("red"))
    {
        System.Threading.Thread.Sleep(750);
        figure = "yellow";
        Invalidate();
        System.Threading.Thread.Sleep(750);
        figure = "green";
        Invalidate();   
    }           
    else if (figure.Equals("green"))
    {
        System.Threading.Thread.Sleep(750);
        figure = "yellow";
        Invalidate();
        System.Threading.Thread.Sleep(750);
        figure = "red";
        Invalidate();               
    }

}

我正在编程一个简单的交通信号,我想如果你能按一次"开关"按钮,它会看起来更好,从红色到黄色再到绿色,而不是每次都按它。然而,现在当我运行程序时,它不是等待0.75秒来绘制黄色,然后再等待0.75秒来绘制绿色,而是等待1.5秒,直接从红色变为绿色,根本不显示黄色。

跳过填充椭圆(c#)

您的问题在MSDN页面上的Invalidate方法中有解释

调用Invalidate方法不会强制同步绘制;来方法后调用Update方法无效的方法。当不带参数调用此方法时,整个客户端区域被添加到更新区域。

所以你需要在第一个Invalidate

之后添加一个Update调用
if (figure.Equals("red"))
{
    System.Threading.Thread.Sleep(750);
    figure = "yellow";
    Invalidate();
    Update();
    System.Threading.Thread.Sleep(750);
    figure = "green";
    Invalidate();   
}           
else if (figure.Equals("green"))
{
    System.Threading.Thread.Sleep(750);
    figure = "yellow";
    Invalidate();
    Update();
    System.Threading.Thread.Sleep(750);
    figure = "red";
    Invalidate();               
}

不需要在第二个Invalidate之后调用Update,因为您的事件处理程序退出,因此系统可以执行对最后一个Invalidate的调用