Tag: c# .Net GUI
c# Measuring a String.
by brian on Feb.21, 2008, under .NET, GUI, c#, c# coding GUI
Often times it is desirable to draw a string with a System.Drawing.Graphics. My problem came when drawing text over an image. The image itself is dark but had light spots in it. This can make seeing the text very difficult. To fix the problem I fill a box behind the text. To do that I need to know how tall and wide the text will be.
The magic function is Graphics.MeasureString. This functions returns the calculated size of the string that is being drawn.
// measure the string StringFormat sf = new StringFormat(); sf.Alignment = StringAlignment.Near; sf.LineAlignment = StringAlignment.Near; SizeF boundry = g.MeasureString(ToString(), font); // draw the string Rectangle textRect = new Rectangle(10, 10, (int)(boundry.Width + 2), (int)(boundry.Height + 2)); g.FillRectangle(Brushes.Black, textRect); g.DrawRectangle(Pens.White, textRect); g.DrawString(ToString(), font, Brushes.Yellow, textRect.X, textRect.Y, sf);
