Draw text on a curve in C#

[draw text on a curve]

The example Draw text on a line segment in C# shows how to draw text that follows a line segment. This example uses that code to draw text on 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 void DrawTextOnPath(Graphics gr, Brush brush, Font font,
    string txt, GraphicsPath path, bool text_above_path)
{
    // Make a copy so we don't mess up the original.
    path = (GraphicsPath)path.Clone();

    // Flatten the path into segments.
    path.Flatten();

    // Draw characters.
    int start_ch = 0;
    PointF start_point = path.PathPoints[0];
    for (int i = 1; i < path.PointCount; i++)
    {
        PointF end_point = path.PathPoints[i];
        DrawTextOnSegment(gr, brush, font, txt, ref start_ch,
            ref start_point, end_point, text_above_path);
        if (start_ch >= txt.Length) break;
    }
}

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 the text can really follow well, this isn’t a problem.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in algorithms, fonts, graphics and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *