Currently, with Window Presentation Foundation (WPF), it is not easy to display a text string that will follow the path of any given geometry. WPF’s
TextEffects provides transformation on individual characters, but trying to use this capability to get the text to follow an arbitrary geometry requires some additional work. Also,
TextEffects is not available in Silverlight. With the control provided here, a given text string can be made to display on any 2D WPF geometry. The control can, for example, display text on an
A sample application and source code has been provided.
To display text on a path, the fundamental problem that must be solved is to figure out how to translate and rotate each character of the string to fit the specified geometry. A big help in solving the problem is the
GetFlattenedPathGeometry() method provided by the
Geometry base class. This method returns a
PathGeometry that approximates the geometry by a series of lines (
LineSegment). For example, the red lines below depict the flattened path of the path geometry (black):
For a good overview of the WPF geometry classes, see MSDN.
The next step in the problem is to take the flattened path geometry and figure out how to transform the characters of the
string to follow the flattened path. The figure below depicts the angle that must be calculated so the letter “
A” will follow the flattened path. In
TextOnAPath, the method ‘
GetIntersectionPoints’ in the
GeometryHelper class calculates the points along the flattened path where the characters intersect with the path. Knowing the intersection points, the angle (and translation) values can then be calculated.
Using the Code
TextOnAPath control is used just like any normal
UIElement in WPF. The XAML below will display the text
string along the curved path, centered in a grid:
Title="Test App" Height="500" Width="500">
<TextOnAPath:TextOnAPath FontSize="30" DrawPath="True"
Text="The quick brown fox jumped over the lazy hen.">
<PathGeometry Figures="M0,0 C120,361 230.5,276.5 230.5,276.5
L308.5,237.50001 C308.5,237.50001 419.5,179.5002 367.5,265.49993
315.5,351.49966 238.50028,399.49924 238.50028,399.49924 L61.500017,
Parameters for the
string to be displayed. If the
text string is longer than the
geometry path, then
text will be truncated.
geometry for the
text to follow.
DrawPath (Boolean): If
true, draws the
geometry below the
DrawLinePath (Boolean): If
true, draws the flattened path
geometry below the
ScaleTextPath (Boolean): If
geometry will be scaled to fit the size of the control.
Points of Interest
- 13th October, 2008
- 29th October, 2008
- Update to fix code that draws
- Provided link to Silverlight version of code