更好的算法褪色一个winform [英] Better algorithm to fade a winform

查看:146
本文介绍了更好的算法褪色一个winform的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当搜寻code褪色一个winform,我碰到这个<少时href=\"http://social.msdn.microsoft.com/forums/en-us/winformsdesigner/thread/B5FE06B9-04E0-499E-93AC-A31B6A87E546\">page在MSDN论坛。

While searching for code to fade a winform, I came across this page on the MSDN forum.

for (double i = 0; i < 1; i+=0.01)
{
    this.Opacity = i;
    Application.DoEvents();
    System.Threading.Thread.Sleep(0);
}

循环有一个非整数递增,而且从previous问题,我问,这不是一个很好的编程技术(由于不精确重新$ P大多数小数$ psentation)。

The for loop has a non-integer increment and, from a previous question I asked, that's not a good programming technique (due to inexact representation of most decimals).

我想出了这个办法。

for (double i = 0; i < 100; ++i)
{
    this.Opacity = i/100;
    Application.DoEvents();
    System.Threading.Thread.Sleep(0);
}

哪一个是更有效?

Which of these is more efficient?

如果有褪色形式更好的算法,我如果包括它很高兴。

If there's a better algorithm for fading a form, I'll be very glad if it is included.

感谢。

推荐答案

忘记定时器(双关语意)。

Forget timers (pun intended).

与Visual Studio 4.5或更高版本,你可以的await 被推迟的任务。这种方法的优点是,它是异步的,不像一个线程睡眠的DoEvents 循环,它在阻止应用程序淡入淡出(和上述其他的DoEvents 的问题)。

With Visual Studio 4.5 or higher, you can just await a task that is delayed. An advantage of this method is that it's asynchronous, unlike a thread Sleep or DoEvents loop, which blocks the application during the fade (and the other aforementioned DoEvents problems).

private async void FadeIn(Form o, int interval = 80) 
{
    //Object is not fully invisible. Fade it in
    while (o.Opacity < 1.0)
    {
        await Task.Delay(interval);
        o.Opacity += 0.05;
    }
    o.Opacity = 1; //make fully visible       
}

private async void FadeOut(Form o, int interval = 80)
{
    //Object is fully visible. Fade it out
    while (o.Opacity > 0.0)
    {
        await Task.Delay(interval);
        o.Opacity -= 0.05;
    }
    o.Opacity = 0; //make fully invisible       
}

用法:

private void button1_Click(object sender, EventArgs e)
{
    FadeOut(this, 100);
}

如果你申请的透明度之前,该对象被设置你应该检查。我使用的形式为对象,但你可以通过支持透明,只要它的正确施放任何对象。

You should check if the object is disposed before you apply any transparency to it. I used a form as the object, but you can pass any object that supports transparency as long as it's cast properly.

这篇关于更好的算法褪色一个winform的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆