Updated: 5/21/2003; 9:59:47 PM.
Chris Goldfarb's Radio Weblog
Blogfarb's Goldblog: Periodic stackdump of all things .NET and Intel
        

Tuesday, March 11, 2003


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;

}


8:39:25 PM    comment []


It has come full circle.

I work for a group that supports various software development efforts at Intel.  One of these efforts is the XBox Performance Libraries group.  Thus, indirectly one could say I've contributed to my 2-year old son's first vice...  An addiction to the XBox game "Loons".

Here he is, strung out after a full half hour of mind-numbing fun.  Should I feel guilty?

I have to wonder - if I pulled out my old Atari 2600 from the closet, dusted it off, and fired up a game of Yar's Revenge, what would he think?

7:42:09 PM    comment []

© Copyright 2003 Chris Goldfarb.
 
March 2003
Sun Mon Tue Wed Thu Fri Sat
            1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31          
Feb   Apr



Subscriptions