翼度科技»论坛 编程开发 .net 查看内容

WPF实现类似ChatGPT的逐字打印效果

6

主题

6

帖子

18

积分

新手上路

Rank: 1

积分
18
背景

前一段时间ChatGPT类的应用十分火爆,这类应用在回答用户的问题时逐字打印输出,像极了真人打字回复消息。出于对这个效果的兴趣,决定用WPF模拟这个效果。
真实的ChatGPT逐字输出效果涉及其语言生成模型原理以及服务端与前端通信机制,本文不做过多阐述,重点是如何用WPF模拟这个效果。
技术要点与实现

对于这个逐字输出的效果,我想到了两种实现方法:

  • 方法一:根据字符串长度n,添加n个关键帧DiscreteStringKeyFrame,第一帧的Value为字符串的第一个字符,紧接着的关键帧都比上一帧的Value多一个字符,直到最后一帧的Value是完整的目标字符串。实现效果如下所示:

  • 方法二:首先把TextBlock的字体颜色设置为透明,然后通过TextEffect的PositionStart和PositionCount属性控制应用动画效果的子字符串的起始位置以及长度,同时使用ColorAnimation设置TextEffect的Foreground属性由透明变为目标颜色(假定是黑色)。实现效果如下所示:

由于方案二的思路与WPF实现跳动的字符效果中的效果实现思路非常类似,具体实现不再详述。接下来我们看一下方案一通过关键帧动画拼接字符串的具体实现。
[code]public class TypingCharAnimationBehavior : Behavior{    private Storyboard _storyboard;    protected override void OnAttached()    {        base.OnAttached();        this.AssociatedObject.Loaded += AssociatedObject_Loaded; ;        this.AssociatedObject.Unloaded += AssociatedObject_Unloaded;        BindingOperations.SetBinding(this, TypingCharAnimationBehavior.InternalTextProperty, new Binding("Tag") { Source = this.AssociatedObject });    }    private void AssociatedObject_Unloaded(object sender, RoutedEventArgs e)    {        StopEffect();    }    private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)    {        if (IsEnabled)            BeginEffect(InternalText);    }    protected override void OnDetaching()    {        base.OnDetaching();        this.AssociatedObject.Loaded -= AssociatedObject_Loaded;        this.AssociatedObject.Unloaded -= AssociatedObject_Unloaded;        this.ClearValue(TypingCharAnimationBehavior.InternalTextProperty);        if (_storyboard != null)        {            _storyboard.Remove(this.AssociatedObject);            _storyboard.Children.Clear();        }    }    private string InternalText    {        get { return (string)GetValue(InternalTextProperty); }        set { SetValue(InternalTextProperty, value); }    }    private static readonly DependencyProperty InternalTextProperty =    DependencyProperty.Register("InternalText", typeof(string), typeof(TypingCharAnimationBehavior),    new PropertyMetadata(OnInternalTextChanged));    private static void OnInternalTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)    {        var source = d as TypingCharAnimationBehavior;        if (source._storyboard != null)        {            source._storyboard.Stop(source.AssociatedObject);            source._storyboard.Children.Clear();        }        source.SetEffect(e.NewValue == null ? string.Empty : e.NewValue.ToString());    }    public bool IsEnabled    {        get { return (bool)GetValue(IsEnabledProperty); }        set { SetValue(IsEnabledProperty, value); }    }    public static readonly DependencyProperty IsEnabledProperty =        DependencyProperty.Register("IsEnabled", typeof(bool), typeof(TypingCharAnimationBehavior), new PropertyMetadata(true, (d, e) =>        {            bool b = (bool)e.NewValue;            var source = d as TypingCharAnimationBehavior;            source.SetEffect(source.InternalText);        }));    private void SetEffect(string text)    {        if (string.IsNullOrEmpty(text) || this.AssociatedObject.IsLoaded == false)        {            StopEffect();            return;        }        BeginEffect(text);    }    private void StopEffect()    {        if (_storyboard != null)        {            _storyboard.Stop(this.AssociatedObject);        }    }    private void BeginEffect(string text)    {        StopEffect();        int textLength = text.Length;        if (textLength < 1  || IsEnabled == false) return;        if (_storyboard == null)            _storyboard = new Storyboard();        double duration = 0.15d;        StringAnimationUsingKeyFrames frames = new StringAnimationUsingKeyFrames();        Storyboard.SetTargetProperty(frames, new PropertyPath(TextBlock.TextProperty));        frames.Duration = TimeSpan.FromSeconds(textLength * duration);        for(int i=0;i

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具