How to use IDrawable in XNA


In this mini article I will show you how to use IDrawable Interface.

In your game project add an extra IDrawable near your Game object and Implement interface "IDrawable". 

1.gif 

It will add this region with some functions and events:

#region IDrawable Members

public new void Draw(GameTime gameTime)
{
  throw new NotImplementedException();
}

public int DrawOrder
{
  get { throw new NotImplementedException(); }
}

public event EventHandler<EventArgs> DrawOrderChanged;

public bool Visible
{
  get { throw new NotImplementedException(); }
}

public event EventHandler<EventArgs> VisibleChanged;

#endregion

Generally Draw function is already being used in the Game1.cs so its better you remove the first one added.Dont forget to insert these codes inside your new Draw Function:

GraphicsDevice.Clear(Color.CornflowerBlue);
base.Draw(gameTime);

So the updated structure will be like that:

public class Game1 : Microsoft.Xna.Framework.Game,IDrawable
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }
    protected override void Initialize()
    {        
        base.Initialize();
    }
    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
    }
    protected override void UnloadContent()
    {
    }
    protected override void Update(GameTime gameTime)
    {
        base.Update(gameTime);
    }

    #region IDrawable Members
    public new void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        base.Draw(gameTime);
    }
    public int DrawOrder
    {
        get { throw new NotImplementedException(); }
    }
    public event EventHandler<EventArgs> DrawOrderChanged;
    public bool Visible
    {
        get { throw new NotImplementedException(); }
    }
    public event EventHandler<EventArgs> VisibleChanged;
    #endregion
}

DrawOrder is used when to decide which DrawableGameComponents should draw in order. Such as:

DrawableGameComponent d3 = new DrawableGameComponent(this);
d3.DrawOrder = 3;
this.Components.Add(d3);

DrawableGameComponent d1 = new DrawableGameComponent(this);
d1.DrawOrder = 1;
this.Components.Add(d1);

DrawableGameComponent d2 = new DrawableGameComponent(this);
d2.DrawOrder = 2;
this.Components.Add(d2);

We can set its order here and draw it in order.

we have an event named DrawOrderChanged.When we set this,this event throws and we can add anything to control draworder functionality.

Visible indicates whether IDrawable.Draw should be called in Game.Draw for the game components.

And we can even know if a visibility changed so;

When adding Idrawable make sure you implement it on a DrawableGameComponent.Its much more useful there.


Similar Articles