为绘制的文本添加gloweffect

时间:2011-09-13 09:48:09

标签: c# wpf

有没有办法为使用绘图上下文的DrawText方法绘制的文本添加效果?特别是我正在寻找一种发光效果。我目前正在绘制这样的文本(在我自己形状的OnRender中继承自UIElement):

...
drawingContext.PushClip(new RectangleGeometry(textrect));
drawingContext.DrawText(formattedText, new Point(textrect.Left, textrect.Top));
drawingContext.Pop();
...

如果可以为绘制的文本添加发光效果,我还需要在后续调用上一行时文本更改时应用它(不知道是否需要额外的工作)。

2 个答案:

答案 0 :(得分:1)

我认为发光效果适用于适当的视觉效果,而不适用于绘图上下文成员,如DrawText()调用。您可以考虑在图形上下文中绘制像TextBlock这样的视觉效果......

<TextBox Width="200">
  <TextBox.BitmapEffect>

    <!-- <BitmapEffectGroup> would go here if you wanted to apply more 
         then one effect to the TextBox. However, in this example only  
         one effect is being applied so BitmapEffectGroup does not need  
         to be included. -->

    <!-- The OuterGlow is blue, extends out 30 pixels, has the 
         maximum noise possible, and is 40% Opaque. -->
    <OuterGlowBitmapEffect GlowColor="Blue" GlowSize="30" Noise="1"
     Opacity="0.4" />

  </TextBox.BitmapEffect>
</TextBox>

然后使用文本块渲染为图像(或者也可以将其绘制到绘图上下文中)

   Visual theVisual = textBlock ; //Put the aimed visual here.
   double width = Convert.ToDouble(theVisual.GetValue(FrameworkElement.WidthProperty));
   double height = Convert.ToDouble(
                       theVisual.GetValue(FrameworkElement.HeightProperty));
   if (double.IsNaN(width) || double.IsNaN(height))
   {
       throw new  FormatException(
          "You need to indicate the Width and Height values of the UIElement.");
   }
   RenderTargetBitmap render = new  RenderTargetBitmap(
          Convert.ToInt32(width),
          Convert.ToInt32(this.GetValue(FrameworkElement.HeightProperty)),
          96,
          96,
          PixelFormats.Pbgra32);
   // Indicate which control to render in the image
   render.Render(this);
   Stream oStream = new  MemoryStream();
   PngBitmapEncoder encoder = new  PngBitmapEncoder();
   encoder.Frames.Add(BitmapFrame.Create(render));
   encoder.Save(oStream);
   oStream.Flush();

如果这有帮助,请告诉我....

答案 1 :(得分:1)

在.NET 4中,UIElement.BitmapEffect已过时且无法呈现。相反,您需要使用UIElement.Effect属性。可供选择的效果较少,但您可以使用具有正确属性设置的DropShadowEffect创建发光效果。

查看此资源:http://karlshifflett.wordpress.com/2008/11/04/wpf-sample-series-solution-for-the-obsolete-bitmapeffect-property-and-rendering-an-outerglowbitmapeffect/(请注意,此示例会为Button添加一个亮点,但它应同等地应用于LabelTextBlock。< / p>