Number Display

In my previous post, I mentioned a Number Display that I had created in order to display numbers to the screen without creating any garbage. I thought some people might find it useful, so here it is. It’s relatively simple. You initialize it with a GraphicsDevice, SpriteFont, and some magnitude to define the general size. The Number Display will then create a number palette to be used in displaying the numbers. To draw a number, use the Draw(…) function passing in the number you want to display. The Number Display will finally use a Spritebatch to draw all of the different digits from the palette. Since no strings are used, no garbage is created.

public class NumberDisplay
    GraphicsDevice drawDevice;
    SpriteBatch drawBatch;
    Texture2D numberTex;
    Rectangle[] aryNumberRects = new Rectangle[10];

    public NumberDisplay(GraphicsDevice newDevice, SpriteFont newFont, int digitMagnitude)
        drawDevice = newDevice;
        drawBatch = new SpriteBatch(drawDevice);

        int rectSize = 2 * digitMagnitude;
        RenderTarget2D newRender = new RenderTarget2D(drawDevice, 10 * rectSize, rectSize, false,
            SurfaceFormat.Color, DepthFormat.None, 0, RenderTargetUsage.PreserveContents);

        // Create draw rects and texture map

        Vector2 digitDim;
        for (int i = 0; i < aryNumberRects.Length; i++)
            digitDim = newFont.MeasureString(i.ToString());
            aryNumberRects[i] = new Rectangle(i * rectSize, 0, rectSize, rectSize);
            drawBatch.DrawString(newFont, i.ToString(), new Vector2(
                aryNumberRects[i].Center.X, aryNumberRects[i].Center.Y), Color.White,
                0.0f, Vector2.Zero, rectSize / Math.Max(digitDim.X, digitDim.Y), SpriteEffects.None, 0.0f);

        numberTex = newRender;

    // ***** ACCESSORS *****

    public Texture2D NumberPalette { get { return numberTex; } }

    // ***** USER METHODS *****

    public void Draw(int drawNum, Vector2 drawPos)
        int drawDigit = drawNum;
            drawDigit = drawNum % 10;
            drawBatch.Draw(numberTex, drawPos, aryNumberRects[drawDigit], Color.White);
            drawPos.X -= aryNumberRects[drawDigit].Width;
            drawNum = drawNum / 10;
        } while (drawNum > 0);
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: