Search code examples
c#.netsystem.drawing

c# system.drawing calculate size of font for 1 character to fill a square image


If I have a System.Drawing.Bitmap with equal dimensions e.g. 100x100, 50x50 and I wanted to use this code to draw in a single character:

StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;

font = new Font(_fontName, _fontSize, _fontStyle);

GraphicsPath path = new GraphicsPath();

path.AddString("A", font.FontFamily, (int)font.Style, font.Size, rect, stringFormat);

How would I go about calculating the value for _fontSize so that it fits tightly inside the dimensions of the image?


Solution

  • Graphics.MeasureString function returns the size of a string of a given font. In a loop you can determine what font size fits best.

    http://msdn.microsoft.com/en-us/library/403ezxd2.aspx