CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Jan 2000
    Location
    Colorado, United States
    Posts
    12

    Question C# and GetTextExtent

    I am writing a control in C#. I would like to get the size of th text in pixels from the Graphics object. This would be similair to DC.GetTExtExtent in VC++.

    I've tried MeasureString but it does not return me what I was expecting.

    Does anyone know how to do this? Is there some mode I have to set to get MeasureString to work as I want?

  2. #2
    Join Date
    Nov 2002
    Location
    Singapore
    Posts
    1,890
    Hi, I have following code written for you which will center the text in a form.

    void DrawWelcomeMessage(string []s)
    {

    PictureBox p = pictureBoxWelcome;
    Image im = p.Image;
    Graphics g = Graphics.FromImage(im);
    System.Drawing.Font f = new Font("Microsoft Sans Serif",12);

    int y = im.Height/2;
    Brush b = new SolidBrush(Color.Red);


    for ( int i=0; i<s.Length; i++)
    {
    if ( i == 1 ) y = y+40;

    SizeF nSize = g.MeasureString(s[i],f);
    int x = (int) (im.Width - nSize.Width)/2;
    g.DrawString(s[i],f,b,x,y);
    y =y + (int)(nSize.Height*0.75);
    }

    g.Dispose();
    p.Invalidate();

    }


    hope it will help you in what you are seeking,

    Paresh

  3. #3
    Join Date
    Jan 2000
    Location
    Colorado, United States
    Posts
    12
    Not really. I'm not looking to center text in a form, I'm looking to compute the with and height in pixels that the text takes up.

    For example in GetTextExtent in VC++ a value of "XXX" with a Arial font of size 10 would have a height of about 8 pixels and a width of about 12 - 15 pixels.

  4. #4
    Join Date
    Nov 2002
    Location
    Singapore
    Posts
    1,890
    that's what
    SizeF nSize = g.MeasureString(s[i],f);
    does. SizeF will give u size u want of the font. make sure u use that particular fonts.
    check out that class properly.
    there is another class also with it.

    Paresh

  5. #5
    Join Date
    Jan 2000
    Location
    Colorado, United States
    Posts
    12

    Wink

    Thanks for the response.

    What was happening was i had the call as follows


    TextSize = pe.Graphics.MeasureString(sValue, hHeaderCell.Font, sValue.Lenth);

    passing in the length seemed to mess up the values. Once I removed the length it works great.

    Thanks again. Sorry about the misunderstanding

  6. #6
    Join Date
    Nov 2002
    Location
    Singapore
    Posts
    1,890
    Ah ! I SEE . so good that it got working.
    enjoy
    Paresh

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured