位图效果概述

位图效果使设计人员和开发人员能够将视觉效果应用于呈现的 Windows Presentation Foundation (WPF) 内容。 例如,位图效果允许你轻松地将 DropShadowBitmapEffect 效果或模糊效果应用于图像或按钮。

重要

在 .NET Framework 4 或更高版本中,BitmapEffect 类已过时。 如果尝试使用 BitmapEffect 类,将收到一个过时的异常。 BitmapEffect 类的非过时替代项是 Effect 类。 在大多数情况下,Effect 类的速度更快。

WPF 位图效果

位图效果(BitmapEffect 对象)是简单的像素处理操作。 位图效果将 BitmapSource 作为输入,并在应用效果(例如模糊或投影)后生成新的 BitmapSource。 每个位图效果都公开了可以控制筛选属性的属性,例如 RadiusBlurBitmapEffect

作为一种特殊情况,在 WPF 中,效果可以设置为实时 Visual 对象的属性,例如 ButtonTextBox。 像素处理在运行时应用并呈现。 在这种情况下,在呈现时,Visual 会自动转换为其等效的 BitmapSource,并作为输入提供给 BitmapEffect。 输出将替换 Visual 对象的默认呈现行为。 这就是为什么 BitmapEffect 对象仅强制视觉对象在软件中呈现,即应用效果时不会对视觉对象进行硬件加速。

注释

WPF 位图效果在软件模式下呈现。 应用某种效果的任何对象也将在软件中呈现。 当对大型视觉对象使用位图效果或对位图效果的属性进行动画处理时,性能会降低最多。 这不是说你根本不应该以这种方式使用位图效果,但你应该谨慎和测试,以确保你的用户获得你期望的体验。

注释

WPF 位图效果不支持部分信任执行。 应用程序必须具有完全信任权限才能使用位图效果。

如何应用效果

BitmapEffectVisual的属性。 因此,对视觉对象应用效果(如 ButtonImageDrawingVisualUIElement)与设置属性一样简单。 BitmapEffect 可以设置为单个 BitmapEffect 对象,也可以使用 BitmapEffectGroup 对象链接多个效果。

以下示例演示如何在可扩展应用程序标记语言(XAML)中应用 BitmapEffect

<Button  Width="200">You Can't Read This!
  <Button.BitmapEffect>

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

    <!-- The larger the Radius, the more blurring. The default range is 20.
         In addition, the KernelType is set to a box kernel. A box kernel
         creates less disruption (less blur) then the default Gaussian kernel. -->
    <BlurBitmapEffect Radius="10" KernelType="Box" />

  </Button.BitmapEffect>
</Button>

以下示例演示如何在代码中应用 BitmapEffect

// Get a reference to the Button.
Button myButton = (Button)sender;

// Initialize a new BlurBitmapEffect that will be applied
// to the Button.
BlurBitmapEffect myBlurEffect = new BlurBitmapEffect();

// Set the Radius property of the blur. This determines how
// blurry the effect will be. The larger the radius, the more
// blurring.
myBlurEffect.Radius = 10;

// Set the KernelType property of the blur. A KernalType of "Box"
// creates less blur than the Gaussian kernal type.
myBlurEffect.KernelType = KernelType.Box;

// Apply the bitmap effect to the Button.
myButton.BitmapEffect = myBlurEffect;

注释

BitmapEffect 应用于布局容器(如 DockPanelCanvas)时,效果将应用于元素或视觉对象的可视化树,包括其所有子元素。

创建自定义效果

WPF 还提供非托管接口来创建可在托管 WPF 应用程序中使用的自定义效果。 有关创建自定义位图效果的其他参考资料,请参阅 非托管 WPF 位图效果 文档。

另请参阅