为WPF中DropShadowBitmapEffect提供轻量级的替代品
周银辉
WPF有一个激动人心的新特性:我们可以很方便地为可视元素提供位图效果(BitmapEffect),比如阴影等.但令人沮丧饿是位图效果是非常消耗CPU资源的,从平时的开发中我们几乎可以得出的两条经验:1,尽量少地使用位图效果,因为它是由CPU计算的而不是GPU. 2,不要将位图效果与稍稍复杂一点的动画(Animation)使用,它常常使动画变得很不流畅.
在位图效果中,最常用的当数阴影(DropShadowBitmapEffect),这里有一个DropShadowBitmapEffect的替代品SystemDropShadowChrome,其虽算不上完美,但在很多时候却是一个不错的解决DropShadowBitmapEffect性能问题的方法.
我们可以使用一个SystemDropShadowChrome对象,其将充当"阴影",然后将我们需要添加阴影的对象作为SystemDropShadowChrome对象的Child,这与将一个对象作为的Border的子对象一样.
![SystemDropShadowChrome.png](https://i-blog.csdnimg.cn/blog_migrate/3150dcfedc324c5242ba2ae7d8921fe5.png)
在上图中,淡蓝色方块的阴影效果便是使用我们的SystemDropShadowChrome得到的,桔黄色方块的阴影效果是使用DropShadowBitmapEffect得到的.你可以粘贴下面的代码到XamlPad查看:
<
Page
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:a
="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero"
>
<
Grid
Width
="579"
Height
="492"
>
![None.gif](/Images/OutliningIndicators/None.gif)
<
a:SystemDropShadowChrome
Width
="75"
CornerRadius
="3,13,3,13"
RenderTransformOrigin
="0.5,0.5"
HorizontalAlignment
="Left"
Margin
="185,149,0,0"
x:Name
="systemDropShadowChrome"
VerticalAlignment
="Top"
Height
="75"
>
<
Border
Background
="LightBlue"
CornerRadius
="3,13,3,13"
Margin
="1,1,1,1"
/>
</
a:SystemDropShadowChrome
>
![None.gif](/Images/OutliningIndicators/None.gif)
<
Border
Background
="#FFE78E16"
CornerRadius
="3,13,3,13"
RenderTransformOrigin
="0.5,0.5"
HorizontalAlignment
="Left"
Margin
="185,0,0,132"
x:Name
="border"
VerticalAlignment
="Bottom"
Width
="75"
Height
="75"
>
<
Border
.BitmapEffect
>
<
DropShadowBitmapEffect
ShadowDepth
="2"
/>
</
Border.BitmapEffect
>
</
Border
>
</
Grid
>
</
Page
>
另外,阴影的颜色也是可以设定的,我们只需设置SystemDropShadowChrome对象的Color属性即可.
但很不幸运的是SystemDropShadowChrome对象不能为设置其他形状的元素设置阴影,因为它自身的形状只能做到方形与圆角方形.
你可以点击
这里 或
这里查看更多的关于SystemDropShadowChrome的讨论