Alpha 混合淡入/淡出图像






4.50/5 (3投票s)
如何显示图像淡入/淡出效果。
引言
我一直尝试模仿 Windows Vista 操作系统使用的淡入效果。以下是如何将这种美妙的效果应用到您的图像上。
使用代码
首先,我们需要两张图像,它们会根据情况相互重叠。
正常状态
鼠标悬停在图像上
我们首先声明我们需要全局变量
Dim increase As Boolean = True
Dim speed As Single = 0.05 'The speed is: 0 to 1
speed
变量可以配置。较高的值对应于较高的效果速度。
现在,我们可以在定时器 Tick
事件中编写代码(间隔 = 1 毫秒,或更小的值)
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
现在,我们必须在正确的时间激活效果:使用 PictureBox
,我们可以使用 MouseEnter
和 MouseLeave
事件。
在这些事件中,我们必须始终激活定时器。在 MouseEnter
中,我们设置 increase = True
,在 MouseLeave
中,我们设置 increase = False
。
关注点
我也尝试了逐像素替换... 太慢了!有必要锁定位图... 它有效,但代码比这个长。而且,这个也更简洁!
历史
- 2009年3月27日 - 首次版本。