在 PictureBox 上透明的 Moveable PictureBox

Moveable PictureBox transparent over PictureBox

我有两个图片框,一个是玩家控制的(pic1),另一个是不动的(pic2)。我想拥有它,所以当 pic1 在 pic2 上时,pic1 的背景是透明的,所以我们可以看到 pic2。目前,这就是我所拥有的。

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    pic2.BringToFront()
    pic1.BringToFront()
    If e.KeyData = Keys.D Then
        pic1.Left += 5
    End If
    If e.KeyData = Keys.A Then
        pic1.Left -= 5
    End If
    If e.KeyData = Keys.W Then
        pic1.Top -= 5
    End If
    If e.KeyData = Keys.S Then
        pic1.Top += 5
    End If
End Sub

有什么帮助吗?还是我的编码方式不可能?

创建此类游戏的最佳方法是使用 OpenGL、DirectX、XNA 等,但您也可以使用 GDI+ 和 Graphics.DrawImage

但是您应该知道的一件事是,在编程方面几乎没有什么是不可能的。 :)

这是我用于具有适当透明背景的图片框的解决方案。请记住,将图片框移到其他 controls/pictureboxes 上可能会导致它滞后,因为它必须递归地重绘它后面的所有内容:

1) 首先,创建一个自定义组件(在 VS/VB 的 "Add New Item" 菜单中找到)。

2) 给它一个你选择的名字(例如:TransparentPictureBox)。

3) 让它继承原来的PictureBox.

Public Class TransparentPictureBox
    Inherits PictureBox

End Class

4) 将以下代码粘贴到 class:

Protected Overrides Sub OnPaintBackground(e As System.Windows.Forms.PaintEventArgs)
    MyBase.OnPaintBackground(e)

    If Parent IsNot Nothing Then
        Dim index As Integer = Parent.Controls.GetChildIndex(Me)

        For i As Integer = Parent.Controls.Count - 1 To index + 1 Step -1
            Dim c As Control = Parent.Controls(i)
            If c.Bounds.IntersectsWith(Bounds) AndAlso c.Visible = True Then
                Dim bmp As New Bitmap(c.Width, c.Height, e.Graphics)
                c.DrawToBitmap(bmp, c.ClientRectangle)
                e.Graphics.TranslateTransform(c.Left - Left, c.Top - Top)
                e.Graphics.DrawImageUnscaled(bmp, Point.Empty)
                e.Graphics.TranslateTransform(Left - c.Left, Top - c.Top)
                bmp.Dispose()
            End If
        Next
    End If
End Sub

这段代码覆盖了 PictureBox 的 OnPaintBackground 事件,因此通过将它后面的每个控件绘制到背景上来绘制它自己的背景。

5) 构建您的项目(如果您不知道如何构建,请参见下图)。

6) Select 工具箱中的组件并将其添加到表单中。

希望对您有所帮助!


构建您的项目

在 Visual Basic 中打开 Build 菜单并按 Build <your project name here>

从工具箱添加组件