In this article we will learn how to use CreatePatternBrush along with CreateBitmap API. CreateBitmap can be used to create a memory bitmap of specified width, height and Bits/Pixel. CreatePatternBrush can create a pattern brush based of Bitmap. You can also use VB Picture object as a bitmap handle. Picture object has Handle property which you can pass to CreatePatternBrush.
Here is the full example
Step-By-Step example
- Create a standard exe project, form1 is added by default - Add two picturebox controls and one commandbutton on the form1 - Add the following code in form1 code window. |
Click here to copy the following block | Private Type RECT Left As Long Top As Long Right As Long Bottom As Long End Type
Private Declare Function CreatePatternBrush Lib "gdi32" ( _ ByVal hBitmap As Long) As Long Private Declare Function FillRect Lib "user32" ( _ ByVal hdc As Long, lpRect As RECT, ByVal hBrush As Long) As Long Private Declare Function SetRect Lib "user32" ( _ lpRect As RECT, ByVal X1 As Long, ByVal Y1 As Long, ByVal X2 As Long, _ ByVal Y2 As Long) As Long Private Declare Function DeleteObject Lib "gdi32" ( _ ByVal hObject 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
Dim bBytes(1 To 64) As Byte
Private Sub DoPattern() Dim R As RECT, mBrush As Long, hBitmap As Long
mBrush = CreatePatternBrush(Me.Picture.Handle) SetRect R, 0, 0, Picture1.ScaleWidth, Picture1.ScaleHeight
FillRect Picture1.hdc, R, mBrush
DeleteObject mBrush
Dim c As Integer For I = 1 To 64 c = c + 1 If c <= 2 Then bBytes(I) = 1 Else bBytes(I) = 255 c = 0 End If Next
hBitmap = CreateBitmap(8, 8, 1, 8, bBytes(1)) mBrush = CreatePatternBrush(hBitmap) SetRect R, 0, 0, Picture2.ScaleWidth, Picture2.ScaleHeight
FillRect Picture2.hdc, R, mBrush
DeleteObject hBitmap End Sub
Private Sub Command1_Click() DoPattern End Sub
Private Sub Form_Load() Me.Picture = LoadPicture(App.Path & "\test.bmp") Command1.Caption = "Create Pattern Brush" Picture1.ScaleMode = vbPixels Picture2.ScaleMode = vbPixels End Sub |
- Press F5 to run the code |
|