by Daniel Christopher Payne (1 Submission)
Category: Graphics
Compatability: VB.NET
Difficulty: Unknown Difficulty
Originally Published: Wed 8th August 2007
Date Added: Mon 8th February 2021
Rating: (1 Votes)
Custom word wrapping using DrawString and MeasureString from the Graphics object
API Declarations
Public Sub PrintLine(ByRef pObj As Object, ByVal psText As String, ByVal X As Long, ByVal Y As Long, ByRef pBounds As System.Drawing.Rectangle)
Dim lX As Long
Dim lY As Long
Dim lSize As System.Drawing.Size
Dim lGraphics As Graphics
Dim lFont As Font
Dim lBreak As Long
Dim lText As String
Dim lCheck As Long
Dim lChar As String
Dim lStrip As Integer
Dim lDraw As String
Dim lBrush As Brush
Dim lColor As Color
Dim lbStop As Boolean
lGraphics = pObj.creategraphics
lFont = pObj.font
lX = X - pBounds.Left
lY = Y - pBounds.Top
lCheck = 1
lText = psText.Substring(0, lCheck)
lSize = lGraphics.MeasureString(lText, lFont).ToSize
Do While Len(psText) > 0
Do While lSize.Width < pBounds.Width - lX And lbStop = False
lChar = lText.Substring(Len(lText) - 1, 1)
If lChar = " " Or lChar = "-" Or lChar = vbLf Then
If lChar = "-" Then
lStrip = 0
ElseIf lChar = " " Then
lStrip = 1
ElseIf lChar = vbLf Then
lStrip = 2
End If
lBreak = lCheck
End If
lCheck = lCheck + 1
If lCheck <= Len(psText) Then
lText = psText.Substring(0, lCheck)
Else
lText = psText
lbStop = True
End If
lSize = lGraphics.MeasureString(lText, lFont).ToSize
Loop
lbStop = False
If lBreak = 0 Then
lBreak = lCheck - 1
lStrip = 0
End If
If lBreak > Len(lText) Then
lBreak = Len(lText)
End If
lDraw = lText.Substring(0, lBreak - lStrip)
psText = psText.Substring(lBreak)
lStrip = 0
lColor = pObj.forecolor
lBrush = New Pen(lColor).Brush
lGraphics.DrawString(lDraw, lFont, lBrush, X, Y)
Y = Y + lSize.Height
lY = Y - pBounds.Left
lCheck = 1
If Len(psText) > 0 Then
lText = psText.Substring(0, lCheck)
lSize = lGraphics.MeasureString(lText, lFont).ToSize
End If
Loop
End Sub
'put the following on a form with a button named Button1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim lSize As System.Drawing.Rectangle
lSize = New Rectangle(1, 1, 40, 125)
PrintLine(Me, "This is another test of the word-wrap function!", 1, 1, lSize)
End Sub
No comments have been posted about Custom word wrapping using DrawString and MeasureString from the Graphics object. Why not be the first to post a comment about Custom word wrapping using DrawString and MeasureString from the Graphics object.