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

本文关键字:像素 颜色 XNA 何读取 读取 | 更新日期: 2023-09-27 18:01:43

我想要一种方法去发现,例如,游戏窗口上Vector2(2,5)的像素是否为color color。红色,或者其他颜色或者坐标。我该怎么做呢?

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

将纹理转换为数组,然后基于协调查找指定像素并获得颜色。示例可以在remeers 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);
}

您应该首先将图形设备的backbuffer(使用GraphicsDevice.GetBackBufferData())读取到纹理中,然后按照上述方法检查纹理