您似乎不理解
GraphicsDevice.Clear(Color)
的作用。
XNA打开一个Windows窗口并使用DirectX进行绘制。
GraphicsDevice.Clear(Color)
清除使用DirectX绘制的缓冲区,但与窗口无关。
要使窗口透明,您必须修改底层窗口。
为此,您首先必须添加对System.Windows.Forms和System.Drawing的引用。
在Game1类的构造函数中,可以执行以下操作:
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IntPtr hWnd = Window.Handle;
System.Windows.Forms.Control ctrl = System.Windows.Forms.Control.FromHandle(hWnd);
System.Windows.Forms.Form form = ctrl.FindForm();
form.TransparencyKey = System.Drawing.Color.Black;
}
让我们逐行浏览这个内容:
首先两行是自动生成的,我们不需要关注它们。
IntPtr hWnd = Window.Handle;
这行代码可以获取在Windows中注册的底层窗口指针。
System.Windows.Forms.Control ctrl = System.Windows.Forms.Control.FromHandle(hWnd);
这行代码获取给定窗口中的WindowsForms-Control
。
System.Windows.Forms.Form form = ctrl.FindForm();
这行代码可以获取控件所属的表单。
form.TransparencyKey = System.Drawing.Color.Black
这一行代码设置了关键字“
Color
”,用于标识一个单独的
Color
-值,不会被绘制出来。我使用了
Black
,但您也可以选择
CornflowerBlue
。
这将使您的窗口对该Color
内部透明。建议您选择与清除Color
相同的Color
。
需要注意两点:
最佳实践是缓存您的Form
,以便您可以从任何地方设置TransparencyKey
。
您还可以通过以下方式使您的Window
无边框:
form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
希望我能帮到您。
编辑:
我刚意识到这个问题已经几年没有回答了。所以如果您偶然发现它,请随意使用。