Is there a way to dynamically create a generic Texture2D?

52 views Asked by At

I am currently developing an ECS within Monogame as a personal project and I want to set a default Sprite for my Sprite Components. However, I do not want to load in a file from the ContentManager, I want it to be separate before I develop the content pipeline.

Is it possible to instantiate, for instance, a black and white checkerboard Texture2D dynamically without needing to load content from an existing Texture?

In my constructor, I current have this for instantiating

if( texture == null )
{
    this.texture = new Texture2D(Globals.graphicsDevice, 16, 16);
}

However it doesn't appear to display on screen. Should this be coming out as a generic solid-color Texture?

2

There are 2 answers

0
AzuxirenLeadGuy On

You have correctly created a texture of size 16x16 pixels, but it is filled with transparent colour. You need to load white color in it.

So your code will be

if( texture == null )
{
    this.texture = new Texture2D(Globals.graphicsDevice, 16, 16);
    Color[] data = new Color[16*16];
    for(int i=0;i<16*16;i++)data[i]=Color.White;
    this.texture.SetData<Color>(data);
}

It goes without saying that if you want some other colour to be set, you should change that in the loop.

What I prefer to do is to create a texture of 1x1 size of white colour, and use the parameters in Spritebatch.Draw method to scale and color the texture as I wish to.

0
James On

I recommend allocating the texture the size you want, then calling GetData which gives you an array of the correct size, then simply iterate it assigning to the elements, then pass it back to SetData.