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);
}
fffffffffffffffff
test red font.

浙公网安备 33010602011771号