65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 BitBlt 复制图形(.NET 风格)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (12投票s)

2003年12月30日

viewsIcon

201570

downloadIcon

2480

当 Graphics.Clone() 无法满足需求时。

引言

当基本的 GDI+ 函数无法满足需求时,你需要回到 API 学习阶段。BitBlt 简单地复制屏幕的某些部分。这是通过访问 Windows hDC 和其他低级、令人费解的东西来实现的。

首先,我们需要 DeclareGDI32.DLL 文件中的函数,以便在 VB.NET 中使用它们。

Declare Auto Function BitBlt Lib "GDI32.DLL" ( _
     ByVal hdcDest As IntPtr, _
     ByVal nXDest As Integer, _
     ByVal nYDest As Integer, _
     ByVal nWidth As Integer, _
     ByVal nHeight As Integer, _
     ByVal hdcSrc As IntPtr, _
     ByVal nXSrc As Integer, _
     ByVal nYSrc As Integer, _
     ByVal dwRop As Int32) As Boolean

然后,我创建了一个特殊函数,它将复制由 rectangleF 指定的屏幕区域。

Private Function copyRect(ByVal src As PictureBox, _ 
       ByVal rect As RectangleF) As Bitmap
     'Get a Graphics Object from the form
     Dim srcPic As Graphics = src.CreateGraphics
     'Create a EMPTY bitmap from that graphics
     Dim srcBmp As New Bitmap(src.Width, src.Height, srcPic)
     'Create a Graphics object in memory from that bitmap
     Dim srcMem As Graphics = Graphics.FromImage(srcBmp)

     'get the IntPtr's of the graphics
     Dim HDC1 As IntPtr = srcPic.GetHdc
     'get the IntPtr's of the graphics
     Dim HDC2 As IntPtr = srcMem.GetHdc

     'get the picture 
     BitBlt(HDC2, 0, 0, rect.Width, _ 
       rect.Height, HDC1, rect.X, rect.Y, 13369376)

     'Clone the bitmap so we can dispose this one 
     copyRect = srcBmp.Clone()

     'Clean Up 
     srcPic.ReleaseHdc(HDC1)
     srcMem.ReleaseHdc(HDC2)
     srcPic.Dispose()
     srcMem.Dispose()
     srcMem.Dispose()
End Function

然后,我们只需要调用该函数来返回所需的图像

Dim bmp = CType(copyRect(src, _ 
    New RectangleF(0, 0, 50, src.Height)), Bitmap)    
dest.Image = bmp.CloneShorthand:

-或-

dest.Image = CType(copyRect(src, _ 
   New RectangleF(0, 0, 50, src.Height)), Bitmap).Clone

这两个语句中的任何一个都会克隆 src 图像在 (0,0,50, src.height) 处的部分,并返回一个 bitmap 对象。我只是简单地将 bitmap 对象克隆到一个 picturebox 中,以便你可以看到结果。

© . All rights reserved.