Determine if String fits within Rectangle

fightclub777

New member
Joined
Aug 20, 2007
Messages
2
Programming Experience
3-5
Hi guys,

I can't seem to figure out how to do this. Basically, I'm printing several labels from a windows form app. Since each labels is a very specific size, I need to check if my string will fit within the label rectangle (after applying the font attributes and such).

Please note that rectangle itself is of a dynamic height, as there are other content prior to it.

Here is a snippet:

VB.NET:
Dim sNotes As String = IsThereNotes(sJobNumber)  'Function that returns notes as string.

If sNotes > "" Then
                    TextYPos = TextYPos + 30
                    Dim yy As Integer 
                    Dim lbl As New Label

                    yy = (yLimit + 1) * 250

                    lbl.Text = sNotes
                    lbl.AutoSize = True
                    lbl.Font = printFontSm
                    lbl.Width = 300

                    Dim rect As New RectangleF
                    rect.Size = New Size(300, yy - TextYPos)
                    rect.Location = New Point(430, TextYPos)

'PERFORM SIZE CHECK HERE
                    If ([COLOR="Red"]##sNOTES##[/COLOR]> rect.Height) Then
                        'Notes DO NOT FIT. Insert Exclamation Point Instead.
                        sNotes = "Please check system for important notes"
                        e.Graphics.DrawImage(My.Resources.Resource1.Exclamation, New Point(430, TextYPos))
                        e.Graphics.DrawString(sNotes, printFont10, Brushes.Black, 450, TextYPos)
                    Else
                        e.Graphics.DrawString(sNotes, printFont10, Brushes.Black, rect)
                    End If
                End If

Obviously, the ##sNOTES## needs to be replaced with something that i can check against the rectangle height.
I've tried creating a label control and assigning the .text property to my string, and then checking the label height, but this did not work.

If there is another way I should be doing this, outside of using a label, I'm all ears.

Any help is greatly appreciated.
 
Last edited:
Resolved

Ok, with the help of someone else, I was able to figure it out. Here is how you can measure a string with the Graphics.MeasureString() method:


VB.NET:
Dim lblSize As SizeF = e.Graphics.MeasureString(sNotes, printFont10, 300)

If (lblSize.Height > rect.Height) Then

....

End If

The "300" above refers to the width of the string.
 
Back
Top