What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleDraw text that follows a curve in Visual Basic .NET
DescriptionThis example shows how to draw text that follows a curve in Visual Basic .NET.
Keywordsgraphics, algorithms, fonts, rotated text, text on segment, line segment, Visual Basic .NET, VB.NET
CategoriesAlgorithms, Graphics, Graphics

The example Draw text that sits above or below a line segment in Visual Basic .NET shows how to draw text that follows a line segment. This example uses that code to draw the pieces of code that follow a curve. The DrawTextOnPath method shown in the following code uses the previous example's DrawTextOnSegment method to draw text that follows a GraphicsPath.

' Draw some text along a GraphicsPath.
Private Sub DrawTextOnPath(ByVal gr As Graphics, ByVal brush _
    As Brush, ByVal font As Font, ByVal txt As String, ByVal _
    path As GraphicsPath, ByVal text_above_path As Boolean)
    ' Make a copy so we don't mess up the original.
    path = DirectCast(path.Clone(), GraphicsPath)

    ' Flatten the path into segments.

    ' Draw characters.
    Dim start_ch As Integer = 0
    Dim start_point As PointF = path.PathPoints(0)
    For i As Integer = 1 To path.PointCount - 1
        Dim end_point As PointF = path.PathPoints(i)
        DrawTextOnSegment(gr, brush, font, txt, start_ch, _
            start_point, end_point, text_above_path)
        If (start_ch >= txt.Length) Then Exit For
    Next i
End Sub
The code first makes a copy of the GraphicsPath so it can modify it without messing up the original. It then flattens the path to turn it into a series of line segments. (Note that a GraphicsPath may contain more than one disconnected "figure." This example does not take that into account and assumes all of the resulting segments are connected.)

The code then loops through the path's points and calls the DrawTextOnSegment method to draw as many characters as will fit on the current line segment.

If no characters fit on a line segment, the code keeps its current starting point and uses the next point as the end point of a segment on which to draw. That means if the path curves tightly the text may end up written over parts of it. For reasonably smooth curves, which are the only ones that text can really follow well, this isn't a problem.

Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.