How to create an Alphabet bitmap in CSharp

Letters generated by the programHere’s another short utility. I have been looking for a decent alphabet to look in my next game (called HogWash) . As before, I want to create a sprite sheet with letters. But every alphabet set that I found had issues with kerning. I kid you not, usually but not always with M, W, or even Q.

Even when I put together a sprite sheet manually, the editor didn’t quite get it right and letters didn’t quite fit the grid. So to simplify it, here;’s a 50 line C# program that takes the letters you supply in a string, combined with a font (Liberation Mono- from Red Hat) and a brush (black solid). It does a double loop that I exit with a goto (shock horror!) when it reaches the a terminating * in the string I supplied.

That is the graphic file above that the program below generated. As you can see the letters are far enough apart so no overlapping. Just put in your path where I have for the source and dest consts. You can use this technique for building sprite sheet.

// Author D. Bolton Learncgames.com You are free to use and copy this program as you wish but please leave this line in.
using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace buildfont
{
    class Program
    {
        const int LetterWidth = 100;
        const int LetterHeight = 120;
        const string source = "Your path"
        const string dest = @"YourPath\letters.png";

        static Bitmap allLetters = new Bitmap(LetterWidth * 8,LetterHeight * 5);

        static void Main(string[] args)
        {
            BuildOneImage();
        }

        private static void BuildOneImage()
        {
            var font = new Font("Liberation Mono",95);
            var brush = new SolidBrush(Color.Black);
            var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ*";
            Console.WriteLine("Creating letters.png");
            var aty = 0.0f;
            using (Graphics g = Graphics.FromImage(allLetters))
            {
                var strindex = 0;
                for (var y = 0; y < 5; y++)
                {
                    var atx = 0.0f;
                    for (int x = 0; x < 6; x++)
                    {
                        string aLetter = str[strindex++].ToString();
                        if (aLetter == "*") goto Done;
                        g.DrawString(aLetter, font, brush, atx, aty);
                        atx += LetterWidth;
                    }
                    aty += LetterHeight;
                }
            }
            Done:
            allLetters.Save(dest, ImageFormat.Png);
        }
    }
}