ApachePilotMPE
ApachePilotMPE

Reputation: 193

How can I read the color of a specific pixel in XNA?

I want a way to find out if, for example, the pixel at Vector2(2, 5) on the game window is color Color.Red, or some other color or set of coordinates. How can I do this?

Upvotes: 2

Views: 2340

Answers (2)

Davor Mlinaric
Davor Mlinaric

Reputation: 2027

Convert texture into array, and then based on coordinated find specified pixel and get color. Example can be found here on Reimers XNA webpage.

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]; 
        }
    }
    return colors2D;
}

converting color to argb

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);
}

Upvotes: 2

Wouter
Wouter

Reputation: 2262

You should first read the backbuffer (using GraphicsDevice.GetBackBufferData()) of the graphics device into a texture and then inspect the texture as described above.

Upvotes: 0

Related Questions