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);
Leave a Reply
You must be logged in to post a comment.

September 7th, 2010 on 4:38 am
Buy:Viagra.Maxaman.Soma.Viagra Super Active+.Viagra Professional.Cialis Professional.Viagra Soft Tabs.Cialis Soft Tabs.Levitra.Viagra Super Force.VPXL.Zithromax.Cialis Super Active+.Super Active ED Pack.Cialis.Propecia.Tramadol….
November 10th, 2010 on 9:18 pm
…
BUY FASHION. TOP BRANDS: GUCCI, DOLCE&GABBANA, BURBERRY, DIESEL, ICEBERG, ROBERTO CAVALLI, EMPORIO ARMANI, VERSACE…