弹来弹去跑马灯!

WPF 打字效果

利用 StringAnimationUsingKeyFrames:

 

 public ChatGPTWindow()
        {
            InitializeComponent();
            txt1.Text = "";//Textblock control
            TypewriteTextblock("我爱北京天安门,我爱祖国,我爱北京天安门,我爱祖国,我爱北京天安门,我爱祖国,我爱北京天安门,我爱祖国,我爱祖国我爱祖国我爱祖国", txt1);

        }
        private void TypewriteTextblock(string textToAnimate, TextBlock txt)
        {

            TimeSpan timeSpan = TimeSpan.FromSeconds(textToAnimate.Length/2);//相当于速度
            Storyboard story = new Storyboard();
            story.FillBehavior = FillBehavior.HoldEnd;
            story.RepeatBehavior = RepeatBehavior.Forever;

            DiscreteStringKeyFrame discreteStringKeyFrame;
            StringAnimationUsingKeyFrames stringAnimationUsingKeyFrames = new StringAnimationUsingKeyFrames();
            stringAnimationUsingKeyFrames.Duration = new Duration(timeSpan);

            string tmp = string.Empty;
            foreach (char c in textToAnimate)
            {
                discreteStringKeyFrame = new DiscreteStringKeyFrame();
                discreteStringKeyFrame.KeyTime = KeyTime.Paced;
                tmp += c;
                discreteStringKeyFrame.Value = tmp;
                stringAnimationUsingKeyFrames.KeyFrames.Add(discreteStringKeyFrame);
            }
            Storyboard.SetTargetName(stringAnimationUsingKeyFrames, txt.Name);
            Storyboard.SetTargetProperty(stringAnimationUsingKeyFrames, new PropertyPath(TextBlock.TextProperty));
            story.Children.Add(stringAnimationUsingKeyFrames);

            story.Begin(txt);
        }

  

posted @ 2023-03-05 22:02  wgscd  阅读(100)  评论(0)    收藏  举报