Centering text using GDI+ and MeasureString
The GDI+ Graphics object comes chock full of great stuff. One of the nicer capabilities however, is a method called MeasureString. This method literally takes a string, and given the Font context, returns a SizeF containing the width and height. Not that impressive, until you stumble upon the need to do something like I had to recently do, in which case it's a lifesaver.
Here's a method I created which takes a string, and using the Graphics reference that the object is being rendered to, selects the best size and fit to center the text.
public bool DrawCenteredText(string Text, int FontSize, bool Bold, int VerticalPosition, Graphics g, Color TextColor, int HorizontalAdjust)
{
try
{
Font f;
if (Bold)
f = new Font("Arial", FontSize, FontStyle.Bold);
else
f = new Font("Arial", FontSize);
// Keep shrinking the font until it fits within our object
// If the font gets too small, start hacking off chars
SizeF stringSize = g.MeasureString(Text, f);
while (Convert.ToInt32(stringSize.Width) > this.Width)
{
if (FontSize > 4)
{
FontSize--;
if (Bold)
f = new Font("Arial", FontSize, FontStyle.Bold);
else
f = new Font("Arial", FontSize);
}
else
Text = Text.Substring(0, Text.Length - 1);
// Measure the string again
stringSize = g.MeasureString(Text, f);
}
SolidBrush b = new SolidBrush(this.ForeColor);
// Set the string formatting
StringFormat drawFormat = new StringFormat();
drawFormat.FormatFlags = StringFormatFlags.NoWrap;
drawFormat.Alignment = StringAlignment.Center;
RectangleF drawRect;
drawRect = new RectangleF(this.XPos - HorizontalAdjust, this.YPos + VerticalPosition, this.Width, this.Height);
// Draw string to screen
g.DrawString(Text, f, b, drawRect, drawFormat);
b.Dispose();
f.Dispose();
drawFormat.Dispose();
}
catch
{
return false;
}
return true;
}