[疑难杂症]如何消除BitmapEffect的遗留效果

    在 WPF 中,可以使用 BitmapEffect 对象为每一个 Visual 对象生成各种各样的效果,这些效果包括:

    OuterGlowBitmapEffect(外发光)、DropShadowBitmapEffect(阴影)、EmbossBitmapEffect(浮雕)、BlurBitmapEffect(模糊)、BevelBitmapEffect(斜角)。

     

    如果文字想要拥有这些效果,则可以直接将这些效果应用到TextBlock控件上。效果如下图:

     

     

    文字即拥有外发光的效果,代码如下:

     

        <TextBlock Name="txt" FontSize="40" VerticalAlignment="Center" HorizontalAlignment="Center" Text="xirihanlin">

            <TextBlock.BitmapEffect>

                <OuterGlowBitmapEffect GlowSize="5" GlowColor="Green" Opacity="0.5"/>

            </TextBlock.BitmapEffect>

        </TextBlock>

     

    如果文字是由动画产生时,即0秒文字内容为“xirihanlin”,5秒后变为“”,代码如下:

     

        _sb = new Storyboard();

        _sb.FillBehavior = FillBehavior.Stop;

        ObjectAnimationUsingKeyFrames frames = new ObjectAnimationUsingKeyFrames();

        Storyboard.SetTargetName(frames, this.txt.Name);

        Storyboard.SetTargetProperty(frames, new PropertyPath(TextBlock.TextProperty));

        frames.KeyFrames.Add(new DiscreteObjectKeyFrame("xirihanlin", KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0))));

        frames.KeyFrames.Add(new DiscreteObjectKeyFrame("", KeyTime.FromTimeSpan(TimeSpan.FromSeconds(5))));

        _sb.Children.Add(frames);

     

    当动画结束时,一个奇怪的事情出现了,如下图所示:

     

     

    动画结束(或播放过程中Stop动画)时,明明是把文字置为空了,为什么还显示外发光效果以及之前的文字(甚至产生了偏移)呢?

     

    具体原因我也不清楚,猜测是BitmapEffect的效果遗留(极有可能是WPFBug)。怎样才能消除它的影响呢?

    1、删除原来应用于TextBlock控件的BitmapEffect效果;

    2、以动画的方式添加BitmapEffect效果;

    代码如下:

     

        frames = new ObjectAnimationUsingKeyFrames();

        Storyboard.SetTargetName(frames, this.txt.Name);

        Storyboard.SetTargetProperty(frames, new PropertyPath(TextBlock.BitmapEffectProperty));

        OuterGlowBitmapEffect effect = new OuterGlowBitmapEffect();

        effect.GlowSize = 5;

        effect.Opacity = 0.5;

        effect.GlowColor = Colors.Green;

        frames.KeyFrames.Add(new DiscreteObjectKeyFrame(effect, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0))));

        frames.KeyFrames.Add(new DiscreteObjectKeyFrame(null, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(5))));

        _sb.Children.Add(frames);

     

    运行之后,当动画结束时,再也不会出现BitmapEffect的遗留效果了。

     

    整体代码见Demo


posted on 2009-02-26 17:29  xirihanlin  阅读(943)  评论(1编辑  收藏  举报