Results 1 to 2 of 2

Thread: Getting size of a string (measurestring)

  1. #1

    Thread Starter
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704

    Getting size of a string (measurestring)

    Ok, I know how to get the size in pixels of a string using measureString...

    Here's my problem:

    I need to resize text to fit inside the dimensions of my user control button.

    I need to be able to have my user control automatically determine the appropriate font size based on how wide or high the control is.

    This is what I got so far:
    VB Code:
    1. 'get size of string to be printed
    2. stringSize = graphics.MeasureString(text, Font)
    3.  
    4. 'if size of string to be printed is larger than the width of the control
    5. If stringSize > Width Then
    6.  
    7. 'need to implement code that will
    8. 'set the font size to something that will
    9. 'fit within the Width of the control
    10.  
    11. 'ie..  Font.Size = Width   (which obviously isnt it, but makes it clear my intentions)

  2. #2

    Thread Starter
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704
    This is a partial response from a PM to me (so no, I'm not nuts for answering my own question 6 months later).

    For controls, in this case, a usercontrol, it can be determined at runtime, how many pixels high or wide a string is by the following means:


    VB Code:
    1. Dim stringsize As New SizeF(Me.CreateGraphics().MeasureString(Me.Text, Me.Font, controlSize, _
    2.          New StringFormat(StringFormatFlags.NoClip)))

    note: me.Text is the text to be measured, using the default font for the usercontrol, me.Font

    This returns a sizeF structure which states how wide and high the string is. Obviously it draws left to right, until it hits the controlSize.Width, and then moves to a new line, and on and on, until it hits the controlSize.Height.

    You can then get the size of the Font from me.Font.SizeInPoints, create a new font resource from the old font, with the caveat of having the source font size value reduced by 1, and retest.

    Not entirely elegant, but close.

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