pfinferno
pfinferno

Reputation: 1945

How to return character of font family given index

I have a font family name and an index of a specific character from that family.

Example: I have the font family "Wingdings 2" and index 33. If you go to http://www.alanwood.net/demos/wingdings-2.html and look at the first item, which is index 33, the character is a ball point pen.

My question is, how can I retrieve the character itself in C#? I need to draw this character in my application.

I've gone through all of the methods and properties of the Font and FontFamily class, but I don't see anything that could help.

Edit: I know how to draw the character using a graphics object, the issue is actually retrieving the character in the first place knowing only the font family and the index of the character in the given font family.

Upvotes: 0

Views: 232

Answers (1)

Sebastian L
Sebastian L

Reputation: 834

To draw a character you could use this snippet of code:

public static Image DawTextFromFontFamily(string text, FontFamily family, Color textColor, Color backColor)
{
     return DrawText(text, new Font(family, 16), textColor, backColor);
}

public static Image DrawText(String text, Font font, Color textColor, Color backColor)
{
        //first, create a dummy bitmap just to get a graphics object
        Image img = new Bitmap(1, 1);
        Graphics drawing = Graphics.FromImage(img);

        //measure the string to see how big the image needs to be
        SizeF textSize = drawing.MeasureString(text, font);

        //free up the dummy image and old graphics object
        img.Dispose();
        drawing.Dispose();

        //create a new image of the right size
        img = new Bitmap((int)textSize.Width, (int)textSize.Height);

        drawing = Graphics.FromImage(img);

        //paint the background
        drawing.Clear(backColor);

        //create a brush for the text
        Brush textBrush = new SolidBrush(textColor);

        drawing.DrawString(text, font, textBrush, 0, 0);

        drawing.Save();

        textBrush.Dispose();
        drawing.Dispose();

        return img;
}

Now you have an image of whatever characters in whatever font you need

Upvotes: 1

Related Questions