Introduction
I have always tried to imitate the fading effect used by the Windows Vista Operating System. Here's how to apply this wonderful effect to your images..
Using the code
To start, we need two images which will overlap each other depending on the situation.
Normal status
Mouse over image
We start by declaring the global variables that we need:
Dim increase As Boolean = True
Dim speed As Single = 0.05
The speed
variable can be configured. A high value corresponds to a high speed of the effect.
We can now write the code in the timer Tick
event (interval = 1 ms, or a lower value):
Static current_alpha As Single = 0.0
Dim i1 As New Bitmap(My.Resources._01)
Dim i2 As New Bitmap(My.Resources._02)
Dim g As Graphics = Graphics.FromImage(i1)
Dim cm As New Imaging.ColorMatrix(New Single()() { _
New Single() {1, 0, 0, 0, 0}, _
New Single() {0, 1, 0, 0, 0}, _
New Single() {0, 0, 1, 0, 0}, _
New Single() {0, 0, 0, current_alpha, 0}, _
New Single() {0, 0, 0, 0, 1}})
Dim ia As New Imaging.ImageAttributes
ia.SetColorMatrix(cm, Imaging.ColorMatrixFlag.Default, Imaging.ColorAdjustType.Bitmap)
g.DrawImage(i2, New Rectangle(0, 0, i2.Width, i2.Height) _
, 0, 0, i2.Width, i2.Height, GraphicsUnit.Pixel, ia)
g.Dispose()
If increase Then
current_alpha += speed
Else
current_alpha -= speed
End If
PictureBox1.Image = i1
If current_alpha >= 1 Then
current_alpha = 1
tmrBlend.Enabled = False
ElseIf current_alpha <= 0 Then
current_alpha = 0
tmrBlend.Enabled = False
End If
Now, we have to activate the effect at the right time: with a PictureBox
, we can use the MouseEnter
and MouseLeave
events.
In these events, we must always activate the timer. In MouseEnter
, we set increase = True
, and in MouseLeave
, we set increase = False
.
Points of interest
I also tried a pixel-by-pixel replace... it was too slow! It was necessary to lock bits... it works, but the code is longer than this. And, this is also cleaner!
History
- 27/03/2009 - First version.