Nathan
Nathan

Reputation: 1347

How to create fade button effect with pictureboxes

I'm trying to create an effect so when the user hovers the mouse over a picturebox, the button fades to a hoverimage, and when they leave, it fades back to the original. I'm using pictureboxes as buttons in a program. I'm doing this because all the buttons will be pictures with no button textures, so I didn't see the point in using a button. Just so you can visualize it, here is the original image:

enter image description here

And the image to fade to:

enter image description here

I could still change these images a bit, but thats the general idea.

How would I go about creating this fading effect? I'm picturing something using timers and opacity settings, but I don't know how any of that stuff could help me solve this.

E: Heres a bit of code I have. It changes from image to image when I hover, but its not a fade, and it looks very choppy.

    private void pictureBox3_MouseEnter(object sender, EventArgs e)
    {
        pictureBox3.Image = pictureBox37.Image;
    }

    private void pictureBox3_MouseLeave(object sender, EventArgs e)
    {
        pictureBox3.Image = pictureBox38.Image;
    }

pictureBox37 and pictureBox38 are invisible reference pictureboxes with the images I need.

Upvotes: 1

Views: 1213

Answers (1)

Jos Bosmans
Jos Bosmans

Reputation: 161

I don't think there's any WinForms support for this kind of animation, so you'd have to do this manually. If you have more than one of these buttons, I recommend creating your own UserControl with this functionality. I can give you some pointers how to do this:

  • Your UserControl will have two Image properties, one for the normal and one for the hover image
  • You'll have to override the OnPaint method to do your own custom painting, blending these two images onto your Graphics according to a position property. This is a float where 0 indicates showing the normal image and 1 the hover image. Any value in between means a blend of these two images. I found some good blending code here.
  • Then you'll need a Timer to update this position dynamically and redraw the button (by calling Invalidate). I recommend using a Windows.Forms.Timer, which has the advantage that its Tick event is always executed on the main Thread, so you don't have to use Invoke to modify your control.
  • And last but not least you override the OnMouseEnter and OnMouseLeave methods, to set this all into motion. These methods could set a positionChange property that indicates in which direction position is changing.

Hope this helps ...

Upvotes: 1

Related Questions