9

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

1 Answers1

12

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);
GMich
  • 567
  • 4
  • 11
  • So for a 32x32 texture, it would be held in a 1024 color long array? –  Sep 06 '15 at 23:43