Практическое руководство. Создание анимации PathGeometry для текста

Можно преобразовать форматированный текст в объект PathGeometry и использовать объект для выделения текста. Например, можно применить анимацию к объекту PathGeometry так, что анимация будет следовать за контуром форматированного текста.

В следующем примере показан форматированный текст, который был преобразован в объект PathGeometry. Анимированный эллипс следует по контуру или штрихам отображенного текста.

Пример форматированного текста, отображенного как геометрическая фигура с анимированным выделением

Сфера, следующая по геометрическому пути текста

Устаревший пример кода

В следующем примере кода используется объект Path для отображения геометрии форматированного текста. Объект Path может нарисовать закрытые или открытые фигуры, несколько фигур и кривые. Создается анимированный Ellipse, который будет следовать по контуру или штрихам форматированного текста.

<!-- Top-left starting point should be half the width of the ellipse so the text strokes align to the center of circle. -->
<Path 
  Canvas.Top="15" 
  Canvas.Left="15" 
  Stroke="SteelBlue"
  StrokeThickness="3" 
  Fill="LightSteelBlue" 
  Name="path" />

<Ellipse
  Canvas.Top="0" 
  Canvas.Left="0"
  Width="30"
  Height="30">

  <Ellipse.Fill>
    <RadialGradientBrush GradientOrigin="0.5,0.5" Center="0.5,0.5" RadiusX="0.5" RadiusY="0.5">
      <RadialGradientBrush.GradientStops>
        <GradientStop Color="Yellow" Offset="0.25" />
        <GradientStop Color="Transparent" Offset="1" />
      </RadialGradientBrush.GradientStops>
    </RadialGradientBrush>
  </Ellipse.Fill>

  <Ellipse.RenderTransform>
    <MatrixTransform />
  </Ellipse.RenderTransform>
  <Ellipse.Triggers>
    <EventTrigger RoutedEvent="FrameworkElement.Loaded">
      <EventTrigger.Actions>
      <BeginStoryboard>
        <Storyboard x:Name="storyboard">
          <MatrixAnimationUsingPath 
            x:Name="matrixAnimation"
            Duration="0:00:40"
            RepeatBehavior="Forever"
            Storyboard.TargetProperty="RenderTransform.Matrix" />
        </Storyboard>
      </BeginStoryboard>
      </EventTrigger.Actions>
    </EventTrigger>
  </Ellipse.Triggers>
</Ellipse>

В следующем примере кода показан способ создания объекта PathGeometry. Объект присваивается свойству Data объекта Path, который отображает преобразованный форматированный текст как геометрическую форму. Затем объект PathGeometry присваивается свойству PathGeometry объекта MatrixAnimationUsingPath, который предоставляет путь для анимированного эллипса для следования.

        ' Display the text string and animate the ellipse to trace the text character outlines.
        Public Sub DisplayText(ByVal textToDisplay As String)
            ' Create a formatted text string.
            Dim formattedText As New FormattedText(textToDisplay, CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, New Typeface("Verdana"), 96, System.Windows.Media.Brushes.Black)

            ' Set the font weight to Bold for the formatted text.
            formattedText.SetFontWeight(FontWeights.Bold)

            ' Build a geometry out of the formatted text.
            Dim geometry As Geometry = formattedText.BuildGeometry(New System.Windows.Point(0, 0))

            ' Create a set of polygons by flattening the Geometry object.
            Dim pathGeometry As PathGeometry = geometry.GetFlattenedPathGeometry()

            ' Supply the empty Path element in XAML with the PathGeometry in order to render the polygons.
            path.Data = pathGeometry

            ' Use the PathGeometry for the matrix animation,
            ' allowing the ellipse to follow the path of the polygons.
            matrixAnimation.PathGeometry = pathGeometry
        End Sub
// Display the text string and animate the ellipse to trace the text character outlines.
public void DisplayText(string textToDisplay)
{
    // Create a formatted text string.
    FormattedText formattedText = new FormattedText(
        textToDisplay,
        CultureInfo.GetCultureInfo("en-us"),
        FlowDirection.LeftToRight,
        new Typeface("Verdana"),
        96,
        System.Windows.Media.Brushes.Black);

    // Set the font weight to Bold for the formatted text.
    formattedText.SetFontWeight(FontWeights.Bold);

    // Build a geometry out of the formatted text.
    Geometry geometry = formattedText.BuildGeometry(new System.Windows.Point(0, 0));

    // Create a set of polygons by flattening the Geometry object.
    PathGeometry pathGeometry = geometry.GetFlattenedPathGeometry();

    // Supply the empty Path element in XAML with the PathGeometry in order to render the polygons.
    path.Data = pathGeometry;

    // Use the PathGeometry for the matrix animation,
    // allowing the ellipse to follow the path of the polygons.
    matrixAnimation.PathGeometry = pathGeometry;
}

См. также

Основные понятия

Рисование форматированного текста