Search code examples
c#xnaxna-4.0monogame

Procedurally generating a Texture2D in Xna/MonoGame


How could I procedurally generate a Texture2D using code? (ex: I want alternating pixels to be black and white on a 32x32 image)


Solution

  • You can create a new texutre using the 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;
        }
    

    Example for 32x32 a black texture

     CreateTexture(device,32,32,pixel => Color.Black);