2014-05-05 30 views
0

我想了解一下,例如,遊戲窗口上Vector2(2,5)的像素是否爲Color.Red或某種其他顏色或一組座標。我怎樣才能做到這一點?如何讀取XNA中特定像素的顏色?

+0

您可以使用與每像素碰撞中使用的方法相同的方法。獲取紋理的顏色數據並循環檢查這些像素是否與其他紋理像素相對照。你只需稍微改變一下就可以得到它,所以你可以使用座標並獲得特定的顏色數據。基本上是顏色或以特定順序存儲在數組中。然後,您只需計算紋理的x和y位置以及要載入正確像素的vector2。另請注意,如果使用縮放紋理,則需要使用矩陣來獲取正確的像素。 – deathismyfriend

+0

我知道如何從紋理等獲取數據,但我想要做的是獲取遊戲窗口中特定像素的顏色,而不是紋理。 – ApachePilotMPE

+0

你將不得不在這一點找出所有的紋理。然後,您可以從上面提到的紋理中獲取顏色。 – deathismyfriend

回答

0

將紋理轉換爲數組,然後基於協調查找指定像素並獲取顏色。例子可以在Reimers XNA的網頁上找到。

private Color[,] TextureTo2DArray(Texture2D texture) 
{ 
    Color[] colors1D = new Color[texture.Width * texture.Height]; 
    texture.GetData(colors1D); 
} 

Color[,] colors2D = new Color[texture.Width, texture.Height]; 
for (int x = 0; x < texture.Width; x++) 
{ 
    for (int y = 0; y < texture.Height; y++) 
    { 
     colors2D[x, y] = colors1D[x + y * texture.Width]; 
    } 
} 

轉換顏色

public static string ToHex(this Color color, bool includeHash) 
{ 
    string[] argb = { 
     color.A.ToString("X2"), 
     color.R.ToString("X2"), 
     color.G.ToString("X2"), 
     color.B.ToString("X2"), 
    }; 
    return (includeHash ? "#" : string.Empty) + string.Join(string.Empty, argb); 
} 
+0

出於好奇,這個方法返回一個十六進制值的顏色嗎? – Jonny

+0

不,但您可以從顏色中去除(a)rgb值。 'color.r.toString(「x2」)'會給你十六進制值或紅色。所以加入「r」「g」「b」會給你hexa的顏色代碼。 –

0

應該首先閱讀後備緩衝圖形設備(使用GraphicsDevice.GetBackBufferData())到ARGB到紋理,然後檢查紋理如上所述。