簡體   English   中英

如何讓整個游戲窗口透明?

[英]How do I make my entire game window transparent?

我正在為暗黑破壞神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);

該行獲取給定Window中的WindowsForms- Control

System.Windows.Forms.Form form = ctrl.FindForm();

此行將為您提供Control所屬的表單。

form.TransparencyKey = System.Drawing.Color.Black;

最后一行設置了鍵 - Color ,它標識了根本不繪制的單個Color值。 我用過Black ,但你也可以選擇CornflowerBlue

這使您的窗口內部對該Color透明。 我建議你應該選擇相同的Color作為你的clear- Color

有兩點需要注意:

  1. 最佳做法是緩存Form以便可以從任何地方設置TransparencyKey

  2. 您也可以通過這種方式使Window無邊框:

form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

希望我能提供幫助。

編輯:我剛剛意識到這是幾年前被問到的,但沒有答案。 如果您偶然發現它,請隨意使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM