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.

    // 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.

3 Responses to Draw text on a curve in C#

  1. Sanjay says:


    This is fantastic piece of code. Thanks!

    I have two questions:
    1. The resultant text on image doesn’t show space(s), even multiple. Any idea?
    2. Is there any ways this can be made to print horizontally center aligned?

    Thanks and regards

    • RodStephens says:

      The problem is that MeasureString doesn’t count trailing spaces so it thinks “A” and “A ” have the same width. That means when you are trying to fit text on a segment, any trailing spaces get eaten and don’t count against used space.

      If you replace calls to gr.MeasureString with a new method that adds room for spaces, it works. See this followup example:

      Draw improved text on a curve in C#

  2. Pingback: Draw improved text on a curve in C# - C# HelperC# Helper

Leave a Reply

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