我正在为暗黑破坏神3做一个小覆盖(仅供个人使用!)我只想在屏幕中间画一个文本字符串(我们稍后会看到字体)。但对于XNA,我找不到如何将背景设置为透明…到目前为止,我的代码是:
GraphicsDevice.Clear(new Color(0, 0, 0, 255));
spriteBatch.Begin();
spriteBatch.DrawString(font, this.TestToShow, new Vector2(23, 23), Color.White);
spriteBatch.End();
所以我只需要一件事:让这个黑色透明!
您似乎不了解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;
希望我能帮忙。
编辑:我刚意识到这是几年前的问题,但没有答案。所以,如果你偶然发现它,请随意使用它。