how to use System.Drawing.Graphics.MeasureString?

Last post 06-25-2009 11:56 AM by SGWellens. 1 replies.

Sort Posts:

  • how to use System.Drawing.Graphics.MeasureString?

    06-25-2009, 11:49 AM
    • Member
      15 point Member
    • Inx
    • Member since 03-26-2009, 6:18 PM
    • Posts 113

    Hi!

    Im need to get the width of a string..but I cant realy figure out how to use this method...Im currently doing the following..

    System.Drawing.Graphics.MeasureString(lnkBtnMenuObjectMiddle[i].Text, lnkBtnMenuObjectMiddle[i].Font).Width;

    but it wont work...

    any ideas?


  • Re: how to use System.Drawing.Graphics.MeasureString?

    06-25-2009, 11:56 AM
    Answer
    • All-Star
      88,946 point All-Star
    • SGWellens
    • Member since 01-02-2007, 9:27 PM
    • Twin Cities, MN
    • Posts 7,260
    • Moderator
      TrustedFriends-MVPs

     Here is a sample:

        /// ---- TextToBitmap ----------------------------
        ///
        /// using System.Drawing;
        /// using System.Drawing.Imaging;
        /// Author: Steve Wellens
        /// 
        /// <summary>
        /// Takes a Text string and returns a bitmap of the string
        /// </summary>
    
        public static Bitmap TextToBitmap(String TheText)
        {
            Font DrawFont = null;
            SolidBrush DrawBrush = null;
            Graphics DrawGraphics = null;
            Bitmap TextBitmap = null;
            try
            {
                // start with empty bitmap, get it's graphic's object
                // and choose a font
                TextBitmap = new Bitmap(1, 1);
                DrawGraphics = Graphics.FromImage(TextBitmap);
                DrawFont = new Font("Arial", 16);
    
                // see how big the text will be
                int Width = (int)DrawGraphics.MeasureString(TheText, DrawFont).Width;
                int Height = (int)DrawGraphics.MeasureString(TheText, DrawFont).Height;
    
                // recreate the bitmap and graphic object with the new size
                TextBitmap = new Bitmap(TextBitmap, Width, Height);
                DrawGraphics = Graphics.FromImage(TextBitmap);
    
                // get the drawing brush and where we're going to draw
                DrawBrush = new SolidBrush(Color.Black);
                PointF DrawPoint = new PointF(0, 0);
    
                // clear the graphic white and draw the string
                DrawGraphics.Clear(Color.White);
                DrawGraphics.DrawString(TheText, DrawFont, DrawBrush, DrawPoint);
    
                return TextBitmap;
            }
            finally
            {
                // don't dispose the bitmap, the caller needs it.
                DrawFont.Dispose();
                DrawBrush.Dispose();
                DrawGraphics.Dispose();
            }
        }
    


     

    Steve Wellens

    My blog
Page 1 of 1 (2 items)