Bee Eee Blog

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);
:
2 comments for this entry:
  1. CASEY


    CheapTabletsOnline.Com. Canadian Health&Care.Special Internet Prices.No prescription online pharmacy.Best quality drugs. Low price drugs. Buy drugs online

    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….

  2. WILLIE


    NEW FASHION store. Original designers collection at low prices!!! 20 % TO 70 % OFF. END OF SEASON SALE!!!

    BUY FASHION. TOP BRANDS: GUCCI, DOLCE&GABBANA, BURBERRY, DIESEL, ICEBERG, ROBERTO CAVALLI, EMPORIO ARMANI, VERSACE…

Leave a Reply

You must be logged in to post a comment.

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...