关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

云南大王-WPF使用Animation仿WeChat(微信)播放语音消息

发布时间:2020-04-13 00:00:00
效果图预览   新建MyCustomControl类。 public class MyCustomControl : Control { private static Storyboard MyStory; private ObjectAnimationUsingKeyFrames MyAnimation; private List ImageList; private UIElement animation; public static readonly DependencyProperty DurationProperty = DependencyProperty.Register("Duration", typeof(TimeSpan), typeof(MyCustomControl), new PropertyMetadata(null)); /// /// 动画时间 /// public TimeSpan Duration { get { return (TimeSpan)GetValue(DurationProperty); } set { SetValue(DurationProperty, value); } } public static readonly DependencyProperty IsLitProperty = DependencyProperty.Register("IsLit", typeof(bool), typeof(MyCustomControl), new PropertyMetadata(false, new PropertyChangedCallback(OnIsLitChanged))); /// /// 是否开始播放 /// public bool IsLit { get { return (bool)GetValue(IsLitProperty); } set { SetValue(IsLitProperty, value); } } public override void OnApplyTemplate() { base.OnApplyTemplate(); animation = Template.FindName("animation", this) as UIElement; if (animation != null && IsLit) Animate(animation); } private static void OnIsLitChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { bool newValue = (bool)e.NewValue; if (newValue) { MyCustomControl c = d as MyCustomControl; if (c != null && c.animation != null) { c.Animate(c.animation); } } else { MyStory.Stop(); } } private void Animate(UIElement animation) { int count = 0;//计数 for (double i = Duration.TotalSeconds; i > 1; i--) { if (count > 2) { count = 0; } MyAnimation.KeyFrames.Add( new DiscreteObjectKeyFrame() { Value = ImageList[count], KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(Duration.TotalSeconds - i)) }); count++; } Storyboard.SetTarget(MyAnimation, animation); Storyboard.SetTargetProperty(MyAnimation,new PropertyPath(Image.SourceProperty)); MyStory.Children.Add(MyAnimation);//将动画添加到动画板中 Console.WriteLine($"一共添加:{MyAnimation.KeyFrames.Count} 个 DiscreteObjectKeyFrame。"); MyStory.Begin(); } public MyCustomControl() { MyStory = new Storyboard(); MyAnimation = new ObjectAnimationUsingKeyFrames(); MyAnimation.FillBehavior = FillBehavior.Stop; MyAnimation.Completed += (s, args) => { IsLit = false; }; ImageList = new List(); ImageList.Add(new BitmapImage(new Uri("pack://application:,,,/Images/0.png"))); ImageList.Add(new BitmapImage(new Uri("pack://application:,,,/Images/1.png"))); ImageList.Add(new BitmapImage(new Uri("pack://application:,,,/Images/2.png"))); } } 修改MainWindow.xaml。 新增资源(3张)。   MainWindow.xaml.cs新增Grid_MouseLeftButtonDown。   private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (this.AudioPlay.IsLit) { this.AudioPlay.IsLit = false; } else { this.AudioPlay.IsLit = true; } }    

/template/Home/Zkeys/PC/Static