Predict label size

Last post 10-08-2008 16:18 by fredym. 2 replies.
Page 1 of 1 (3 items)
Sort Posts: Previous Next
  • 10-07-2008 17:51

    • fredym
    • Top 75 Contributor
    • Joined on 02-28-2008
    • Posts 5

    Predict label size

    Hi there.

    Does anyone knows if there is a method to know the required label height for a given text, font and label width? I need to draw a textbox below a label but want to draw it as close as possible to the end of the variable text in the label. Somthing like what the mobile internet explorer does when drawing html forms.

    Thanks.

    Fredy Muñoz | MCSD MCT
  • 10-08-2008 4:31 In reply to

    • Neil
    • OpenNETCF Staff
    • Top 10 Contributor
    • Joined on 07-30-2007
    • North Wales
    • Posts 1,149

    Re: Predict label size

    You should look at Graphics.MeasureString.


  • 10-08-2008 16:18 In reply to

    • fredym
    • Top 75 Contributor
    • Joined on 02-28-2008
    • Posts 5

    Re: Predict label size

    Hi Neil, thanks for the tip. It was helpful but initially it didn't solved my problem.

    I began with the following code:

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles MyBase.Load
    
        Dim text As String = "This is a test text. This is a test text. " & _
                             "This is a test text. This is a test text."
    
        Dim g As Graphics = Me.CreateGraphics
        Dim size As SizeF = g.MeasureString(text, _
                              New Font("Tahoma", 9.0!, FontStyle.Regular))
    
    End Sub
    

    But this way MeasureString always assumes the text will be written in one line so the height is always the same and what varies is the width and my problem is to fit text inside a Label with a fixed width and variable height so I tried to get the Graphics object out of the Label Control, but I got a NotSupportedException.

    Then I found that the Smart Device Framework has its own version of the Graphics object, GraphicsEx, and an overloads of the MeasureString method that includes a 'width' parameter so I ended up with this code: (which does exactly what I want):

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles MyBase.Load
    
        Label3.Text = "This is a test text. This is a test text. " & _
                      "This is a test text. This is a test text."
    
        Dim g As GraphicsEx = GraphicsEx.FromControl(Label3)
        Dim size As SizeF = g.MeasureString(Label3.Text, _
                                New FontEx("Tahoma", 9.0!, FontStyle.Regular), _
                                Label3.Width)
    
        Label3.Height = size.Height
    
    End Sub
    Fredy Muñoz | MCSD MCT
Page 1 of 1 (3 items)