Visual Basic .Net block text justification

Written on June 12th 2007, 14:06 by sYnie

I’m working on a project where I have to use VB.NET to render some text. The problem is, that VB doesn’t provite block text justification by default. Using GDI+ it’s quite easy to get that managed. The resulting text will be displayed on a bitmap, which can be drawn to a picturebox etc. Here’s the code:

Sub BlockJustification(ByRef pic As Bitmap, ByVal txt As String, ByRef x As Short, ByRef y As Short, ByRef w As Short)
Dim g As Graphics
g = Graphics.FromImage(pic)

Dim fnt As New Font(”Times New Roman”, 10)
Dim cnty As Integer = 0

Dim ar As String() = txt.Split(Chr(10) + Chr(13))
For m As Integer = 0 To UBound(ar)
Dim newTxt As String = “”
Dim array As String() = ar(m).Split(” “)
For i As Integer = 0 To UBound(array)
Dim newTxtTmp As String = newTxt + array(i)

If g.MeasureString(newTxtTmp, fnt, 9999999).Width >= w Then
Dim spacearray As String() = newTxt.Split(” “)
Dim spacecnt As Integer = UBound(spacearray) – 1

If spacecnt < 1 Then
newTxt = newTxtTmp
Dim tobreake As String = “”
Do While True
If g.MeasureString(tobreake, fnt, 9999999).Width >= w Then
g.DrawString(tobreake, fnt, Brushes.Black, 0, cnty)
cnty += 15
tobreake = “”
If g.MeasureString(newTxt, fnt, 9999999).Width < = w Then
newTxt += ” ”
Exit Do
End If
End If
tobreake += newTxt.Substring(0, 1)
newTxt = newTxt.Substring(1, newTxt.Length – 1)
Loop
Else
Dim newTxtlength As Integer = 0
For n As Integer = 0 To UBound(spacearray) – 1
newTxtlength += g.MeasureString(spacearray(n), fnt, 9999999).Width
Next
Dim space As Integer = w – newTxtlength
Dim spaceperword As Integer = space / spacecnt
Dim cntmeasure As Integer = 0
Dim dotcnt As Integer = w – (newTxtlength + (spaceperword * spacecnt))
‘MsgBox(”space: ” + space.ToString + ” — wordspace: ” + spaceperword.ToString + ” — measure: ” + newTextlength.ToString + ” — width: ” + w.ToString + ” — spacecnt: ” + spacecnt.ToString + ” — dotcnt: ” + dotcnt.ToString + ” — txt: ‘” + newTxt + “‘”)
For n As Integer = 0 To UBound(spacearray) – 1
g.DrawString(spacearray(n), fnt, Brushes.Black, cntmeasure, cnty)
If n = 0 Then
cntmeasure = cntmeasure + dotcnt
End If
cntmeasure += g.MeasureString(spacearray(n), fnt, 9999999).Width + spaceperword
Next
g.DrawLine(Pens.Blue, cntmeasure – spaceperword, 0, cntmeasure – spaceperword, 300)
i -= 1
newTxt = “”
cnty += 15
End If
Else
newTxt += array(i) + ” ”
End If
Next
If Not newTxt = “” Then
g.DrawString(newTxt, fnt, Brushes.Black, 0, cnty)
cnty += 15
End If
Next
g.Dispose()
End Sub

Now you can use it like this:

Dim img As New Bitmap(500, 500)
BlockJustification(img, Text1.Text, 0, 0, 250)
PictureBox1.CreateGraphics.DrawImage(img, 0, 0)

  1. No comments yet.
  1. No trackbacks yet.