Essential WPF 心得2-文字與動畫結合

摘要:WPF 心得2-文字與動畫結合


<!--前端-->
<Window x:Class="WPFTEST.Window3"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window3" Height="300" Width="612" Loaded="Window_Loaded">
    <TextBlock FontSize="72" Name="_text" Width="563">
        soda soda green
       
    <TextBlock.Foreground><LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5"><GradientStop Color="#FF009D00" Offset="0" /><GradientStop Color="#FF3FB49F" Offset="1" /></LinearGradientBrush></TextBlock.Foreground></TextBlock>
</Window>


<!--後端-->
 public Window3()
        {
            InitializeComponent();
            Storyboard perChar = new Storyboard();
            _text.TextEffects = new TextEffectCollection();

            for (int i = 0; i < _text.Text.Length; i++)
            {
                TextEffect effect = new TextEffect();
                effect.Transform = new TranslateTransform();
                effect.PositionStart = i;
                effect.PositionCount = 1;
                _text.TextEffects.Add(effect);

                DoubleAnimation anim = new DoubleAnimation();
                anim.To = 5;
                anim.AccelerationRatio = .5;
                anim.DecelerationRatio = .5;
                anim.RepeatBehavior = RepeatBehavior.Forever;
                anim.AutoReverse = true;
                anim.Duration = TimeSpan.FromSeconds(2);
                anim.BeginTime = TimeSpan.FromMilliseconds(250 * i);
                Storyboard.SetTargetProperty(anim,
                    new PropertyPath("TextEffects[" + i + "].Transform.Y"));
                Storyboard.SetTargetName(anim, _text.Name);

                perChar.Children.Add(anim);
            


            }
            perChar.Begin(this);
        }

 

 

利用此效果,可讓每個字元在不同的時間中移動。