locked
how to use System.Drawing.Graphics.MeasureString? RRS feed

  • Question

  • User-949104918 posted

    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?


    Thursday, June 25, 2009 11:49 AM

Answers

  • User187056398 posted

     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();
            }
        }
    


     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 25, 2009 11:56 AM