Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fading out an image with transparency in WinForms UI (.NET3.5)

The application: I am writing a little game that would teach the user to read music notes. The game play is very simple. The app displayes a note and my little daughter (target user) should hit the emulated keyboard key on the WinForm GUI matching to the note. She has 1 minute to get as many good hits a she can. Successes and failures are counted.

The task: As she hits a good/bad keyboard key, I want to confirm immediately if she was right or wrong without interrupting the play. My plan is to show an OK or a FAILED bitmap that fades out gradually and becomes completely transparent within ~2 seconds. Fading the bitmap out is a nice way to encourage the user to concentrate on the next note and not to bother about the previous result anymore.

The technical question: How can I display a bitmap on a Windows Form with transparency? Or do you have alternative non-intrusive, easy-to-implement ideas on letting the user know of the current good/bad choice?

like image 438
Mr. Lame Avatar asked Jun 06 '09 22:06

Mr. Lame


2 Answers

As dylantblack says, WPF gives you better tools to do this. If you choose to use Windows forms, here's a simple approach using a timer that fades the image out. Set up a timer with whatever frequency you like. Start the timer, increment alpha every time through, and draw white or whatever your form color is with increasing alpha channel value.

int alpha = 0;

...

private void timer1_Tick(object sender, EventArgs e)
{
    if (alpha++ < 255)
    {
        Image image = pictureBox1.Image;
        using (Graphics g = Graphics.FromImage(image))
        {
            Pen pen = new Pen(Color.FromArgb(alpha, 255, 255, 255), image.Width);
            g.DrawLine(pen, -1, -1, image.Width, image.Height);
            g.Save();
        }
        pictureBox1.Image = image;
    }
    else
    {
        timer1.Stop();
    }
}
like image 52
Michael Petrotta Avatar answered Nov 04 '22 02:11

Michael Petrotta


In WinForms you'd need to use timers or something to animate the opacity of the OK or FAILED control to make it fade out, or do something similar using GDI+ to draw it manually.

If you're using .NET 3.5 anyway, I'd recommend using WPF, which is much easier for doing that sort of thing.

As an example, you can have a look at Scott Hanselman's Baby Smash app, which is open source and has a similar concept of fading things in and out.

like image 3
dylantblack Avatar answered Nov 04 '22 00:11

dylantblack