Creating a fade out label

Theun Arbeider picture Theun Arbeider · Mar 29, 2011 · Viewed 16.7k times · Source

This might seem like a simple question...

I'm looking for the Label.Opacity property in C# Winforms.

What I wish to do is have a method that fade's out a label gradually. By means of a timer perhaps?

Since there is not Opacity I'm trying to set it's transperency to higher numbers untill it's high enough that the item should be invisible. But I can't seem to make this work.

Currently I have:

public FadeLabel()
{
    MyTimer timer = new MyTimer();
    this.TextChanged += (s, ea) =>
    {
        if (timer.IsActive)
        {
            timer.Reset();
        }
        else
        {
            timer.WaitTime.Miliseconds = 500;
            timer.Start();
            timer.Completed += (a) =>
            {
                int i = 0;
                Timer tm = new Timer();
                tm.Interval = 1;
                tm.Tick += (sa, aea) =>
                {
                    i++;
                    this.ForeColor = Color.FromArgb(i, Color.Black);
                    this.BackColor = Color.FromArgb(i, Color.White);
                    this.Invalidate();
                    if (i == 255)
                    {
                        tm.Stop();
                    }
                };
                tm.Start();
            };
        }
    };
}

Answer

Zerato picture Zerato · Aug 4, 2013

This is what I'm using to fade out labels:

    label1.Text = "I'm fading out now";
    label1.ForeColor = Color.Black;
    timer1.Start();

    private void timer1_Tick(object sender, EventArgs e)
    {
        int fadingSpeed = 3;
        label1.ForeColor = Color.FromArgb(label1.ForeColor.R + fadingSpeed, label1.ForeColor.G + fadingSpeed, label1.ForeColor.B + fadingSpeed);

        if (label1.ForeColor.R >= this.BackColor.R)
        {
            timer1.Stop();
            label1.ForeColor = this.BackColor;
        }
    }

Maybe not the best solution but I'm still a beginner so this is what I can contribute with. I put timer1.Interval at minimum and played with fadingSpeed until it looked good.