日期:2012-02-28  浏览次数:20388 次


透明位图绘制方法在网上见得很多,多数是采用事先做好一个Mask图,这方法优点是速度快,但就是太麻烦,灵活性差。
任意指定透明色,当然经常也要用到,为此,API提供了一个函数TransparentBlt,可这个函数,非常让人遗憾,VB的API浏览器中不带它是有道理的,因为,它在Win98下有严重内存漏洞,你若有98系统,可试一下:
for i=1 to 20000
TransparentBlt ....
next
同样的图片,在我的XP下16毫秒可完成,但在98下用了14秒,而且,提示系统资源不足,当机了!

下面我写了一个函数就是可以代替TransparentBlt的一种方法,速度当然会慢些,但在任何系统下都可放心使用。

Private Type BITMAP
    bmType As Long
    bmWidth As Long
    bmHeight As Long
    bmWidthBytes As Long
    bmPlanes As Integer
    bmBitsPixel As Integer
    bmBits As Long
End Type
Private Declare Function GetCurrentObject Lib "gdi32" (ByVal hdc As Long, ByVal uObjectType As Long) As Long
Private Declare Function GetObj Lib "gdi32" Alias "GetObjectA" (ByVal hObject As Long, ByVal nCount As Long, lpObject As Any) As Long
Private Declare Function SetBkColor Lib "gdi32" (ByVal hdc As Long, ByVal crColor As Long) As Long

Private Declare Function CreateBitmap Lib "gdi32" (ByVal nWidth As Long, ByVal nHeight As Long, ByVal nPlanes As Long, ByVal nBitCount As Long, lpBits As Any) As Long
Private Declare Function GetPixel Lib "gdi32" (ByVal hdc As Long, ByVal X As Long, ByVal y As Long) As Long
Private Declare Function BitBlt Lib "gdi32" (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 dwRop As Long) As Long
Private Declare Function StretchBlt Lib "gdi32" (ByVal hdc 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 nSrcWidth As Long, ByVal nSrcHeight As Long, ByVal dwRop As Long) As Long

Public Function TranBlt(DestHdc As Long, X As Long, y As Long, w As Long, h As Long, srcHdcOrBmp As Long, Optional srcX As Long, Optional srcY As Long, Optional srcW As Long, Optional srcH As Long, Optional tc As Long = -1, Optional IsBmp As Boolean) As Long
    'srcHdcOrBmp参数 传入的可以是hdc也可以是Bmp对象的Handle,
    'IsBmp参数 为真时srcHdcOrBmp代表Bmp对象的Handle,为假时代表hdc
    '返回值 成功时返回透明色,不成功时返回-1
    Dim tHdc(3) As MemHdc
    Dim j As Long, oc As Long, i As Long, Bm As BITMAP, cc As Long, NewDc As Long
    Dim sw As Long, sh As Long, sBmp As Long, sHdc As Long, obm As Long, NewX As Long, NewY As Long
    If DestHdc = 0 Or srcHdcOrBmp = 0 Or w = 1 And h = 1 Then GoTo fail
    If IsBmp Then   '若传入的是Bmp句柄,需为其创建一个临时DC
        sBmp = srcHdcOrBmp
        tHdc(3) = NewMyHdc(DestHdc, 0, 0, srcHdcOrBmp)
        sHdc = tHdc(3).hdc
    Else
        sHdc = srcHdcOrBmp
        If srcW = 0 Then sBmp = GetCurrentObject(sHdc, 7)
    End If
    If sHdc = 0 Or sBmp = 0 Then GoTo fail
    If srcW = 0 Then    '若没有提供源图大小,需取得整个源图大小
        GetObj sBmp, Len(Bm), Bm
        sw = Bm.bmWidth - srcX
        sh = Bm.bmHeight - srcY
    Else
        sw = srcW
        sh = srcH
    End If
    If sw < 1 Or sh < 1 Then GoTo fail
    If tc = -1 Then
        cc = GetPixel(sHdc, srcX, srcY)       '将左上角第一个像素作为源图背景色,用于透明
    Else