在Xna / MonoGame中以程序方式生成Texture2D

mad*_*ads 3 c# xna xna-4.0 monogame

如何使用代码以程序方式生成Texture2D?(例如:我希望交替像素在32x32图像上为黑白)

小智 6

您可以使用GraphicsDevice创建一个新的纹理。

    public static Texture2D CreateTexture(GraphicsDevice device, int width,int height, Func<int,Color> paint)
       {
        //initialize a texture
        Texture2D texture = new Texture2D(device, width, height);

        //the array holds the color for each pixel in the texture
        Color[] data = new Color[width * height];
        for(int pixel=0;pixel<data.Count();pixel++)
        {
            //the function applies the color according to the specified pixel
            data[pixel] = paint(pixel);
        }

        //set the color
        texture.SetData(data);

        return texture;
    }
Run Code Online (Sandbox Code Playgroud)

黑色纹理32x32的示例

 CreateTexture(device,32,32,pixel => Color.Black);
Run Code Online (Sandbox Code Playgroud)