【问题标题】:Skipping a FillEllipse (C#)跳过 FillEllipse (C#)
【发布时间】:2016-10-25 20:01:05
【问题描述】:
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 秒并直接从红色变为绿色,而不是显示黄色完全没有。

【问题讨论】:

  • 您是否尝试在 Invalidate 后调用 Update 和 Refresh ?

标签: c# drawing


【解决方案1】:

您的问题在 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 的调用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-08
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    相关资源
    最近更新 更多