如何读取XNA中特定像素的颜色?

时间:2014-05-05 00:05:21

标签: c# colors xna coordinates pixel

我想要一种方法来确定,例如,游戏窗口上的Vector2(2,5)上的像素是Color.Red,还是其他颜色或坐标集。我怎么能这样做?

2 个答案:

答案 0 :(得分: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]; 
        }
    }
    return colors2D;
}

将颜色转换为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);
}

答案 1 :(得分:0)

您应首先将图形设备的后备缓冲区(使用GraphicsDevice.GetBackBufferData())读入纹理,然后如上所述检查纹理。