This program repeatedly makes a picture fade to another and back. Variable m_Alpha determined how opaque the first image is.
When the program's Timer fires, the event handler makes a ColorMatrix to manipulate the color components for the pixels in the first image. The matrix looks mostly like the identity matrix so the pixels' red, green, and blue components are not changed. The entry of 0.0 in position (3, 3) sets the pixel's alpha component to 0. The value of m_Alpha in entry (4, 3) then adds m_Alpha to the zero alpha value. The result is that every pixel in the image has its alpha component set to m_Alpha.
After defining the ColorMatrix, the program assigns the matrix to an ImageAttribute object and draws the first image into an output Bitmap with this object.
The program then repeats these steps to draw the second picture onto the output Bitmap while setting each pixel's alpha component to 1 - m_Alpha.
After drawing the two pictures, the program displays the result and increments or decrements m_Alpha. When m_Alpha reaches 0 or 1, the program changes m_DAlpha so the changes to m_Alpha switch direction.
|
Private m_Alpha As Single = 0 ' Alpha on a 0-1 scale.
Private m_DAlpha As Single = 0.05
Private Sub tmrDisplayFrame_Tick(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
tmrDisplayFrame.Tick
Dim bm1 As Bitmap = picSrc1.Image.Clone
Dim bm2 As Bitmap = picSrc2.Image.Clone
Dim image_attr As New ImageAttributes
Dim cm As ColorMatrix
Dim bm As New Bitmap(bm1.Width, bm1.Height)
Dim gr As Graphics = Graphics.FromImage(bm)
Dim rect As Rectangle = _
Rectangle.Round(bm1.GetBounds(GraphicsUnit.Pixel))
cm = New ColorMatrix(New Single()() { _
New Single() {1.0, 0.0, 0.0, 0.0, 0.0}, _
New Single() {0.0, 1.0, 0.0, 0.0, 0.0}, _
New Single() {0.0, 0.0, 1.0, 0.0, 0.0}, _
New Single() {0.0, 0.0, 0.0, 0.0, 0.0}, _
New Single() {0.0, 0.0, 0.0, m_Alpha, 1.0}})
image_attr.SetColorMatrix(cm)
gr.DrawImage(bm1, rect, 0, 0, bm1.Width, bm2.Width, _
GraphicsUnit.Pixel, image_attr)
cm = New ColorMatrix(New Single()() { _
New Single() {1.0, 0.0, 0.0, 0.0, 0.0}, _
New Single() {0.0, 1.0, 0.0, 0.0, 0.0}, _
New Single() {0.0, 0.0, 1.0, 0.0, 0.0}, _
New Single() {0.0, 0.0, 0.0, 0.0, 0.0}, _
New Single() {0.0, 0.0, 0.0, 1 - m_Alpha, 1.0}})
image_attr.SetColorMatrix(cm)
gr.DrawImage(bm2, rect, 0, 0, bm1.Width, bm2.Width, _
GraphicsUnit.Pixel, image_attr)
picResult.Image = bm
picResult.Refresh()
m_Alpha += m_DAlpha
If m_Alpha > 1 Then
m_Alpha = 1
m_DAlpha *= -1
ElseIf m_Alpha < 0 Then
m_Alpha = 0
m_DAlpha *= -1
End If
End Sub
|