如何在WPF中的文本上创建多个笔划?

Bra*_*NET 9 c# wpf

我试图在WPF中创建看起来像这样的文本:

示范文本

请注意,它是黄色文本,黑色笔划,然后是黄色笔划,然后是另一个(非常薄)黑色笔划.现在,我可以创建一个单一的按照与有点难行程创建轮廓文本:如何.请注意,未显示的属性都是包含控件的DP.

protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
{
    // Draw the outline based on the properties that are set.
    drawingContext.DrawGeometry(Fill, 
                                new System.Windows.Media.Pen(Stroke, StrokeThickness), 
                                _textGeometry);
}

/// <summary> 
/// Create the outline geometry based on the formatted text. 
/// </summary> 
public void CreateText()
{
   System.Windows.FontStyle fontStyle = FontStyles.Normal;
   FontWeight fontWeight = FontWeights.Medium;

   if (Bold == true) fontWeight = FontWeights.Bold;
   if (Italic == true) fontStyle = FontStyles.Italic;

   // Create the formatted text based on the properties set.
   FormattedText formattedText = new FormattedText(
      Text,
      CultureInfo.GetCultureInfo("en-us"),
      FlowDirection.LeftToRight,
      new Typeface(
          Font,
          fontStyle,
          fontWeight,
          FontStretches.Normal),
      FontSize,
      System.Windows.Media.Brushes.Black
    );

    // Build the geometry object that represents the text.
     _textGeometry = formattedText.BuildGeometry(new System.Windows.Point(0, 0));
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,我该怎么做并添加另一个(或其他几个)笔画呢?

Bra*_*NET 4

一种方法是将笔画几何形状与初始几何形状组合,然后为第二笔画绘制该几何形状。

幸运的是,.NET 证明Geometry.GetWidenedPathGeometry可以获取笔画几何形状。然后您可以使用Geometry.Combine将两者结合起来:

_combinedGeometry = Geometry.Combine(_textGeometry, 
        _textGeometry.GetWidenedPathGeometry(new Pen(Stroke, StrokeThickness * 2)), 
        GeometryCombineMode.Union, null);
Run Code Online (Sandbox Code Playgroud)

请注意StrokeThickness * 2. 您需要这个,因为 WPF 绘制中心描边,如果没有它,第二个描边将至少部分(如果不是完全)覆盖第一个描边。然后像以前一样绘制,用nullfor Fill:

drawingContext.DrawGeometry(null, 
        new System.Windows.Media.Pen(SecondaryStroke, SecondaryStrokeThickness), 
        _combinedGeometry);
Run Code Online (Sandbox Code Playgroud)

您可以对其他笔画重复此操作,或使用带有循环的集合。

警告GetWidenedPathGeometry根据您使用的字体、字体大小和笔画大小,并不总是返回“完美”笔画。您可能需要稍微尝试一下才能不产生任何伪影。

上述解决方法:如果可能,增加字体大小。它增加了笔划片段之间的距离,降低了算法“桥接”两个笔划片段或创建其他伪影的可能性。