VB.net Measure string width & height – including multi-line strings

Dim fontToMeasure As New Font("Microsoft Sans Serif", 14, FontStyle.Bold)
Dim sizeOfString As New SizeF
Dim g As Graphics = Me.CreateGraphics

sizeOfString = g.MeasureString("This is line 1" & vbcrlf & "This is line 2", fontToMeasure)
Debug.WriteLine("String Height: " & sizeOfString.Height)
Debug.WriteLine("String Width: " & sizeOfString.Width)

If you want to limit the width (so it wraps), use below (300 was my width to set as max):

Dim fontToMeasure As New Font("Microsoft Sans Serif", 14, FontStyle.Bold)
Dim sizeOfString As New SizeF
Dim g As Graphics = Me.CreateGraphics

sizeOfString = g.MeasureString("This is line 1" & vbcrlf & "This is line 2", fontToMeasure, 300)
Debug.WriteLine("String Height: " & sizeOfString.Height)
Debug.WriteLine("String Width: " & sizeOfString.Width)
VB.net Measure string width & height – including multi-line strings

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s