Animate a path like it's drawn on a canvas

前端 未结 3 464
情书的邮戳
情书的邮戳 2021-01-06 03:34

I\'m a newbie in WPF and please, guide me in the right direction for this problem.

I have built a WPF application which contains all the functionality of that of a r

3条回答
  •  悲哀的现实
    2021-01-06 04:08

    TL;DR: We take advantage of the PointAnimationUsingPath. We animate a point along the path and build a Clip geometry as the point is moving.


    Full answer:

    I start by drawing a sample Path in a Grid for demonstration purposes. Put the actual Path data in resources because we will re-use it later.

    
        
            
                
                    
                
            
        
        
    
    

    Then I define an empty Clip geomtery for the Path:

    
        
    
    

    So far, the Path disappeared because it is clipped to an empty geometry. What we have left to do is progressively add points back in this clipping geometry to reveal the Path. For that, we need an object to animate. I suggest to create a FrameworkPoint for the demonstration:

    public class FrameworkPoint : FrameworkElement {
        public static DependencyProperty CenterProperty = DependencyProperty.RegisterAttached("Center", typeof(Point), typeof(FrameworkPoint));
        public Point Center { get => (Point)GetValue(CenterProperty); set => SetValue(CenterProperty, value); }
    
        public event Action CoordinatesChanged;
    
        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) {
            base.OnPropertyChanged(e);
            if (e.Property == CenterProperty) {
                CoordinatesChanged?.Invoke(Center);
            }
        }
    }
    

    This is an object with only one property of type Point, and this property is animatable. Let's add our (invisible) point in the Grid and animate it on our Path:

    
        
            
                
                    
                        
                    
                
            
        
    
    
    

    At start-up, the FrameworkPoint will invisibly follow the Path over the indicated time (10 seconds). All is left to do is build our Clip as the point moves:

    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
            myPoint.CoordinatesChanged += MyPoint_CoordinatesChanged;
        }
    
        private void MyPoint_CoordinatesChanged(Point obj) {
            geometryGroup.Children.Add(new EllipseGeometry(obj, 5, 5));
        }
    }
    

    This won't give perfect results for fast animations because the sampling won't be good enough but it could give you ideas!

提交回复
热议问题