VB.NET Fading out button properly

697 views Asked by At

How do you fade out/in a button in VB.NET properly? I can fadeout/in labels using:

Controls(i).ForeColor = Color.FromArgb(255, alpha, alpha, alpha)

(where Controls(i) is a label from a For Next loop through all controls in Me.Controls; alpha is the value of the RGB, also from a For Next loop).

This did not work for me with buttons because changing the ForeColor leaves the rest of the buttons' UIs visible!

So, the way I'm trying uses a saved Resource image of the button (from a screenshot) and creates a faded in/out version to be displayed as the image in a PictureBox:

Public Function SetImageOpacity(ByVal imgPic As Image, ByVal imgOpac As Double) As Image
    Dim bmpPic As New Bitmap(imgPic.Width, imgPic.Height)
    Dim grPic As Graphics = Graphics.FromImage(bmpPic)
    Dim imgAtt As New ImageAttributes()
    Dim cmxPic As New ColorMatrix()
    cmxPic.Matrix33 = imgOpac
    imgAtt.SetColorMatrix(cmxPic, ColorMatrixFlag.[Default], ColorAdjustType.Bitmap)
    grPic.DrawImage(imgPic, New Rectangle(178, 144, bmpPic.Width, bmpPic.Height), imgPic.Width, imgPic.Height, imgPic.Width, imgPic.Height, GraphicsUnit.Pixel, imgAtt)
    grPic.Dispose()
    imgAtt.Dispose()
    Return bmpPic
End Function

(where imgPic is the Resource image of the button, and imgOpac is the opacity on a scale of 1 to 0, where 0 is transparent).

I then use this image to set my PictureBox's image:

picbox.Image = SetImageOpacity(My.Resources.Nextbutton, 1)

However, I get a glitch where, even though the PictureBox is located at coordinates 178, 144, the image it is showing is displayed at the left edge of the form (i.e. wrong X coordinate), with the Y coordinate correct!

I have a feeling it may lie with my call of .DrawImage(...) (at line 8 of the function) - but the MSDN docs on this subject are very unclear to me.

Please link if this has been asked before!

2

There are 2 answers

0
Idle_Mind On BEST ANSWER

The coordinates in the Graphics grPic are client coords relative to the image itself, not the Form. So (0, 0) is the top left of the image regardless of where that image ends up being displayed in some kind of control.

Try changing it to (0, 0):

grPic.DrawImage(imgPic, New Rectangle(0, 0, bmpPic.Width, bmpPic.Height), imgPic.Width, imgPic.Height, imgPic.Width, imgPic.Height, GraphicsUnit.Pixel, imgAtt)
1
Rob On

why not just use a for loop to change the opacity of the button control from 1 to 0 in increments of say .01 ?