您可能知道,WinForms 控件并非完全设计为支持真正的透明度(Forms 除外,它们实际上可以是透明的)。
另一方面,Bitmaps 支持透明度。
如果您使用支持 Alpha 通道的图像格式(如 .png 位图)创建 Bitmap 对象,则可以在保留其透明度的情况下绘制该图像。
首先要做的是创建一个对象,该对象可用于引用我们要绘制的每个Bitmap,以便我们跟踪它们。
由于您希望能够指定这些对象的位置和大小,因此这是对象必须具有的两个属性。我在这里添加了一些有用的东西。
Public Class BitmapObject
Public Property Name As String
Public Property Image As Bitmap
Public Property Position As Point
Public Property Size As Size
Public Property Order As Integer
End Class
属性Name 将是源文件的名称,Order 将引用Bitmap 相对于容器内绘制的另一个Bitmaps 的z 顺序位置。
所有Bitmaps 都将使用Bitmap 对象的列表进行分组,因此我们可以使用列表索引或其中一个属性来召唤它们。
Public MyBitmaps As List(Of BitmapObject) = New List(Of BitmapObject)
至于绘图表面(画布),我们可以使用Form 本身、PictureBox 或Panel(因为它们或多或少只是表面)。我更喜欢Panel,它很轻巧,可以承载其他控件,并且可以根据需要移动。
如果你想在一个控件上绘图,你只需要订阅它的Paint() 事件并调用控件的Invalidate() 方法来引发它。
Private Sub Panel1_Paint(sender As Object, e As PaintEventArgs) Handles Panel1.Paint
If MyBitmaps.Count > 0 Then
MyBitmaps.OrderBy(Function(item) item.Order).
Select(Function(item)
e.Graphics.DrawImage(item.Image, New Rectangle(item.Position, item.Size))
Return item
End Function).ToList()
End If
End Sub
要将Bitmap 添加到List(Of BitmapObject),由于您想使用OpenFileDialog 让用户选择Bitmap,我们将此功能分配给Button,并且当Bitmap 是选中后,将创建一个新的 BitmapObject 并将其附加到列表中。
Private Sub btnOpenFile_Click(sender As Object, e As EventArgs) Handles btnOpenFile.Click
Dim fd As OpenFileDialog = New OpenFileDialog()
fd.InitialDirectory = "[Images Path]"
Dim dr As DialogResult = fd.ShowDialog()
If dr = Windows.Forms.DialogResult.OK Then
Dim BitmapName As String = New FileInfo(fd.FileName).Name
Using tmpBitmap As Bitmap = New Bitmap(fd.FileName)
MyBitmaps.Add(New BitmapObject With {
.Image = New Bitmap(tmpBitmap),
.Position = New Point(Integer.Parse(TextBox1.Text), Integer.Parse(TextBox2.Text)),
.Size = New Size(tmpBitmap.Height, tmpBitmap.Width),
.Order = MyBitmaps.Count,
.Name = BitmapName})
ComboBox1.Items.Add(BitmapName)
ComboBox1.SelectedIndex = MyBitmaps.Count - 1
TrackBar1.Value = tmpBitmap.Height
TrackBar2.Value = tmpBitmap.Width
Panel1.Invalidate()
End Using
End If
End Sub
这是结果:(Full source code in PasteBin)