图象淡入淡出

来源:互联网 发布:linux移动多个文件 编辑:程序博客网 时间:2024/04/30 13:04
一般传统的实现两个PictureBox之间图像的淡入淡出效果都需要使用大量的API函数并进行复杂的调色板以及绘图设备(Device Context)的操作。但是在Win98、Win2000中,微软提供了支持透明图像拷贝的AlphaBlend函数。
这篇文章就介绍如何通过API函数AlphaBlend实现PictureBox之间图像的淡入淡出效果。AlphaBlend函数的定义在msimg32.dll中,一般Win98、Win2000都带了这个库
    大家可以看到,AlphaBlend函数的定义同普通的复制函数Bitblt很相似,只是最后的参数blendFunct定义为一个rBlendProps结构。那么为什么在函数定义中blendFunct 定义为Long类型呢?因为rBlendProps结构长度是4个字节。而Long类型变量的长度也是4个字节,那么我们就可以程序中通过API函数CopyMemory将一个rBlendProps结构拷贝到blendFunct 中。

    在Form1中添加两个PictureBox控件,其中Picture2为源,Picture1为拷贝目标,将两者的ScaleMode都设置为3-Pixel将两者的AutoRedraw属性都设置为True,然后分别添加图像。在加入一个Timer控件以及一个CommandButton控件,然后在Form1的代码窗口中添加如下代码

Option Explicit
Private Type rBlendProps
    tBlendOp As Byte
    tBlendOptions As Byte
    tBlendAmount As Byte
    tAlphaType As Byte
End Type

Private Declare Function AlphaBlend Lib "msimg32" (ByVal hDestDC As Long, ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hSrcDC As Long, ByVal xSrc As Long, ByVal ySrc As Long, ByVal widthSrc As Long, ByVal heightSrc As Long, ByVal blendFunct As Long) As Boolean
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)

Dim lTime As Byte

Private Sub Command1_Click()
    lTime = 0
    Timer1.Interval = 100
    Timer1.Enabled = True
End Sub

Sub ShowTransparency(cSrc As PictureBox, cDest As PictureBox, ByVal nLevel As Byte)
    Dim LrProps As rBlendProps
    Dim LnBlendPtr As Long
    
    cDest.Cls
    LrProps.tBlendAmount = nLevel
    CopyMemory LnBlendPtr, LrProps, 4
    With cSrc
        AlphaBlend cDest.hDC, 0, 0, .ScaleWidth, .ScaleHeight, .hDC, 0, 0, .ScaleWidth, .ScaleHeight, LnBlendPtr
    End With
    cDest.Refresh
End Sub

Private Sub Timer1_Timer()
    lTime = lTime + 1
    ShowTransparency Picture2, Picture1, lTime
    If lTime >= 255 Then
        Timer1.Enabled = False
    End If
    Me.Caption = Str(Int(lTime / 2.55)) + "%"

End Sub
原创粉丝点击