WPF 文本逐字一个个出现的动画效果

一、效果图:

 

 

二、前台代码:

<Grid>
        <TextBlock Foreground="Transparent" x:Name="text" TextWrapping="Wrap" >
                刚刚想半天都不知道取个什么标题好,我想了又想,还是想不出来
            与 From/To/By 动画类似,关键帧动画对目标属性的值进行动画处理。 它通过其 Duration 在目标值之间创建过渡。 但是,From/To/By 动画可以在两个值之间创建过渡,而单个关键帧动画可以在任意数量的目标值之间创建过渡。 不同于 From/To/By 动画,关键帧动画没有设置其目标值所需的 From、To 或 By 属性。 关键帧动画的目标值使用关键帧对象进行描述,因此称作“关键帧动画”。 若要指定动画的目标值,请创建关键帧对象并将其添加到动画的 KeyFrames 集合。 动画运行时,将在指定的帧之间过渡。
某些关键帧方法除支持多个目标值外,甚至还支持多个内插方法。 动画的内插方法定义了从一个值过渡到下一个值的方式。 有三种内插类型:离散、线性和曲线。

若要使用关键帧动画进行动画处理,需要完成下列步骤。
            <TextBlock.TextEffects>
                <TextEffect PositionCount="5"   x:Name="MyTextEffect">
                    <TextEffect.Foreground>
                        <SolidColorBrush Color="Red"/>
                    </TextEffect.Foreground>
                </TextEffect>
            </TextBlock.TextEffects>
        </TextBlock>
    </Grid>

 

三、后台代码:

Int32AnimationUsingKeyFrames animationUsingKeyFrames= new Int32AnimationUsingKeyFrames();
            int count=text.Text.Length;
            for (int i = 0; i < count; i++)
            {
                animationUsingKeyFrames.KeyFrames.Add(new DiscreteInt32KeyFrame { Value = i, KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(i*0.03)) });
            }
            animationUsingKeyFrames.Duration = TimeSpan.FromSeconds(count*0.03);
            animationUsingKeyFrames.RepeatBehavior = RepeatBehavior.Forever;
            //animationUsingKeyFrames.AutoReverse= true;
            //MyTextEffect.BeginAnimation(TextEffect.PositionCountProperty, animationUsingKeyFrames);
            Storyboard sb=new Storyboard();
            
            Storyboard.SetTarget( animationUsingKeyFrames, text);   
            Storyboard.SetTargetProperty(animationUsingKeyFrames, new PropertyPath("(TextBlock.TextEffects)[0].(TextEffect.PositionCount)"));
            sb.Children.Add(animationUsingKeyFrames);

            ColorAnimation colorAnimation = new ColorAnimation();
            colorAnimation.From = Colors.Black;
            colorAnimation.To = Colors.Blue;
            colorAnimation.Duration = TimeSpan.FromSeconds(1);
            colorAnimation.RepeatBehavior = RepeatBehavior.Forever;
            colorAnimation.AutoReverse = true;
            Storyboard.SetTarget(colorAnimation, text);
            Storyboard.SetTargetProperty(colorAnimation, new PropertyPath("(TextBlock.TextEffects)[0].(TextEffect.Foreground).(SolidColorBrush.Color)"));//(TextEffect.Foreground).(SolidColorBrush.Color)
            sb.Children.Add(colorAnimation);
            sb.Begin();

 

posted @ 2022-12-02 14:16  bdcliang  阅读(435)  评论(0编辑  收藏  举报

bdcliang