|
|
Title | Fit a PictureBox to its non-transparent pixels in VB .NET |
Description | This example shows how to fit a PictureBox to its non-transparent pixels in VB .NET. |
Keywords | shaped picture, PictureBox, region, region |
Categories | Graphics, VB.NET |
|
|
Thanks to Dave Giblin.
When the form loads, the program calls function GetRegion to get a region to represent the pixels in two PictureBoxes that do not have a specific color. It sets the PictureBoxes' Region properties to the regions. That restricts them to those regions. Areas outside of the regions are not drawn and clicks outside the regions fall through to whatever controls lie beneath.
|
|
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
e As System.EventArgs) Handles MyBase.Load
' Get the blast bitmap.
Dim bm_blast As New Bitmap(picX1.Image)
' Set the region to the "non-transparent" pixels.
picX1.Region = GetRegion(bm_blast, bm_blast.GetPixel(0, _
0))
picX2.Image = bm_blast
picX2.Region = GetRegion(bm_blast, bm_blast.GetPixel(0, _
0))
' Get the arrow bitmap.
Dim bm_arrow As New Bitmap(picPlus1.Image)
' Set the region to the "non-transparent" pixels.
picPlus1.Region = GetRegion(bm_arrow, _
bm_arrow.GetPixel(0, 0))
picPlus2.Image = bm_arrow
picPlus2.Region = GetRegion(bm_arrow, _
bm_arrow.GetPixel(0, 0))
End Sub
|
|
The GetRegion function loops through each row of pixels in a Bitmap. It builds rectangles representing the pixels that do not have the specific background color and adds them to the region.
|
|
Private Function GetRegion(ByVal bm As Bitmap, ByVal _
bg_color As Color) As Region
Dim new_region As New Region
new_region.MakeEmpty()
Dim rect As New Rectangle
Dim in_image As Boolean = False
Dim X As Integer
For Y As Integer = 0 To bm.Height - 1
X = 0
Do While (X < bm.Width)
If Not in_image Then
If Not bm.GetPixel(X, Y).Equals(bg_color) _
Then
in_image = True
rect.X = X
rect.Y = Y
rect.Height = 1
End If
ElseIf bm.GetPixel(X, Y).Equals(bg_color) Then
in_image = False
rect.Width = (X - rect.X)
new_region.Union(rect)
End If
X = (X + 1)
Loop
' Add the final piece if necessary.
If in_image Then
in_image = False
rect.Width = (bm.Width - rect.X)
new_region.Union(rect)
End If
Next Y
Return new_region
End Function
|
|
For more information on graphics programming in Visual Basic 6, see my book Visual Basic Graphics Programming.
|
|
|
|
|
|