Search code examples
c#.netwinformsanimationpicturebox

How do I fade a picturebox image to another on mousehover event?


How do I animate a picturebox to change from one image to another on a mouse hover event as a fade-in effect?

I would also like to create the animated picturebox as a control. A toolbox item for ease-of-use

I'm attempting to create this in C# language using .Net 4.5.

Example of a button with what I want to make a picturebox do. Animated Button Example-MSDN


Solution

  • It's better to use WPF if you want to have animations or such thing as it provide animation classes and smooth animating objects.

    Anyways in Winforms you should use a timer for this approach this should work. This is for fading out you can use this to make fade in function. use this on mouse hover on your picturebox. this link explains in detail

    How to fade in and fade out (Fading transition ) image on panel(backgroud image)?

    int opacity = 0;
    
    private void tmrFadeOut_Tick(object sender, EventArgs e)
    {
        if (opacity < 255)
        {
            Image img = myImage.Image;
            using (Graphics g = Graphics.FromImage(img))
            {
                Pen pen = new Pen(Color.FromArgb(opacity, 255, 255, 255), img.Width);
                g.DrawLine(pen, -1, -1, img.Width, img.Height);
                g.Save();
            }
            myImage.Image = img;
            opacity++;
        }
        else
        {
            timer1.Stop();
        }
    }