private static void AnimateToPosition(DependencyObject d, Rect desiredPosition) { Rect position = ArrangePanel.GetPosition(d); if (double.IsNaN(position.X)) { ArrangePanel.SetPosition(d, desiredPosition); } else { Vector vector = desiredPosition.TopLeft - position.TopLeft; double length1 = vector.Length; vector = desiredPosition.BottomRight - position.BottomRight; double length2 = vector.Length; TimeSpan timeSpan = TimeSpan.FromMilliseconds(Math.Max(length1, length2) * 1.0); RectAnimation rectAnimation1 = new RectAnimation(position, desiredPosition, new Duration(timeSpan)); rectAnimation1.DecelerationRatio = 1.0; RectAnimation rectAnimation2 = rectAnimation1; if (!(d is UIElement uiElement)) { return; } uiElement.BeginAnimation(ArrangePanel.PositionProperty, (AnimationTimeline)rectAnimation2); } }
public AnimGroup AddAnimation(RectAnimation ra) { TimeStart = Mathf.Min(TimeStart, ra.TimeStart); TimeEnd = Mathf.Max(TimeEnd, ra.TimeEnd); RectAnimations.Add(ra); return(this); }
/// <summary> /// Arranges the element by optionally animating it to the specified bounds. /// </summary> /// <param name="element">The element to animate and arrange.</param> /// <param name="finalRect">The bounds that the element should use once it is arranged.</param> /// <param name="isAnimated">Whether to animate the element or just arrange it immediately.</param> protected void ArrangeElement(UIElement element, Rect finalRect, bool isAnimated) { if (_animations == null) { throw new InvalidOperationException("Calls to ArrangeElement need to be within BeginArrange/EndArrange calls."); } if (isAnimated && _useAnimation) { Rect currentBounds = (Rect)element.GetValue(BoundsProperty); if ((currentBounds.Width == 0) && (currentBounds.Height == 0)) { Rect initialRect = GetInitialRect(DesiredSize, finalRect, element); element.Arrange(initialRect); currentBounds = initialRect; } RectAnimation animation = new RectAnimation(element, currentBounds, finalRect, _duration); animation.Interpolation = _interpolation; _animations.Add(animation); } else { element.Arrange(finalRect); element.SetValue(BoundsProperty, finalRect); } }
private void TransitionMainText(SceneTransitionRequest str, Image anchorTarget) { var animGroup = new AnimGroup(); var textFadeOut = new FadeAnimation(PhraseText, Time.time, FadeOutDuration, FadeOutCurve, 0.0f); animGroup.AddAnimation(textFadeOut); var lastAnimFinish = textFadeOut.TimeEnd; var defaultTextBoxSize = new Vector2(anchorTarget.rectTransform.rect.width - 30, anchorTarget.rectTransform.rect.height - 35); var requiredHeight = GetDesiredTextHeight(PhraseText, str.TransitionPhrase, defaultTextBoxSize); if (PhraseBackground.rectTransform.anchoredPosition != anchorTarget.rectTransform.anchoredPosition || !Mathf.Approximately(requiredHeight, PhraseText.rectTransform.rect.height)) { var textBoxResize = new RectAnimation(PhraseBackground.rectTransform, textFadeOut.TimeEnd, TransitionDuration, TransitionCurve, anchorTarget.rectTransform); // Fixup for correct size textBoxResize.TargetSize.y = requiredHeight + 35; animGroup.AddAnimation(textBoxResize); lastAnimFinish = textBoxResize.TimeEnd; } var textChange = new SetTextAnimation(PhraseText, lastAnimFinish, str.TransitionPhrase); animGroup.AddAnimation(textChange); var textFadeIn = new FadeAnimation(PhraseText, lastAnimFinish, FadeInDuration, FadeInCurve, 1.0f); animGroup.AddAnimation(textFadeIn); _pendingAnimations.Enqueue(animGroup); }
/// <summary> /// 針對<paramref name="animatable"/>執行泛型動畫。 /// </summary> /// <typeparam name="PropertyType">執行動畫的屬性型別。</typeparam> /// <param name="animatable">要執行動畫的個體。</param> /// <param name="dp">要執行動畫的屬性。</param> /// <param name="to">屬性改變的目標值。</param> /// <param name="durationMs">動畫的時長。</param> public static void BeginAnimation <PropertyType>(this IAnimatable animatable, DependencyProperty dp, PropertyType to, double durationMs) { DependencyObject animation; var duration = TimeSpan.FromMilliseconds(durationMs); switch (to) { case int i: animation = new Int32Animation(i, duration); break; case double d: animation = new DoubleAnimation(d, duration); break; case Color color: animation = new ColorAnimation(color, duration); break; case Thickness thickness: animation = new ThicknessAnimation(thickness, duration); break; case Rect rect: animation = new RectAnimation(rect, duration); break; default: throw new NotSupportedException(); } animatable.BeginAnimation(dp, animation as AnimationTimeline); }
private void DrawSelectedBlockLine(DrawingContext dc) { if (Element.BlockLine == null || !Element.ShowSelectedLine) { return; } var selectedLineHeight = Element.GetSelectedLineHeight(); var timeDrawConverter = Element.TimeDrawConverter; var axisConverter = Element.AxisXConverter; var xStart = axisConverter.DataToScreen(Element.TimeDrawConverter.GetStart(Element.BlockLine)); var xEnd = axisConverter.DataToScreen(timeDrawConverter.GetEnd(Element.BlockLine)); var rect = new Rect(xStart, GetY(), xEnd - xStart, selectedLineHeight); var brush = timeDrawConverter.GetBackground(Element.BlockLine); brush.Freeze(); if (Element.IsNewBlockLine) { var myAnimation = new RectAnimation (new Rect(rect.X, rect.Y, 1, rect.Height), rect, new Duration(TimeSpan.FromMilliseconds(300))); myAnimation.Freeze(); dc.DrawRectangle(brush, null, rect, myAnimation.CreateClock()); Element.IsNewBlockLine = false; } else { dc.DrawRectangle(brush, null, rect); } }
public new System.Windows.Shapes.Path DoThing(RectangleGeometry RectangleGeometry, Grid grid, string spriteName, FrameworkElement frameworkElement) { System.Windows.Shapes.Path myPath = new System.Windows.Shapes.Path { Fill = System.Windows.Media.Brushes.LightGray }; var fullBitmap = new BitmapImage(new Uri(@"pack://application:,,,/Resources/" + SpriteSheetName)); Int32Rect croppRect = new Int32Rect(0, 0, _FrameWidth, _FrameHeight); var croppedBitmap = new CroppedBitmap(fullBitmap, croppRect); JpegBitmapEncoder encoder = new JpegBitmapEncoder(); Guid photoID = System.Guid.NewGuid(); String photolocation = photoID.ToString() + ".jpg"; encoder.Frames.Add(BitmapFrame.Create(fullBitmap)); using (var filestream = new FileStream(photolocation, FileMode.Create)) { encoder.Save(filestream); } ImageBrush mybrush = new ImageBrush(croppedBitmap) { Transform = new TranslateTransform(0, 0), AlignmentX = AlignmentX.Left, AlignmentY = AlignmentY.Top, Stretch = Stretch.Fill }; myPath.Fill = mybrush; myPath.StrokeThickness = 1; myPath.Stroke = System.Windows.Media.Brushes.LightGray; myPath.Data = RectangleGeometry; RectAnimation myRectAnimation = new RectAnimation { BeginTime = TimeSpan.FromSeconds(RandomNumber()), Duration = TimeSpan.FromMilliseconds(RandomNumber(_randomDurationStart, _randomDurationEnd)), FillBehavior = FillBehavior.HoldEnd, // Set the From and To properties of the animation. From = new Rect(RectangleGeometry.Rect.Y, RectangleGeometry.Rect.X, _FrameWidth, _FrameHeight), To = new Rect(RectangleGeometry.Rect.Y, grid.ActualHeight, _FrameWidth, _FrameHeight) }; EventArgs ea = new EventArgs(); myRectAnimation.Completed += new EventHandler(RectAnimation_Completed); // Set the animation to target the Rect property // of the object named "MyAnimatedRectangleGeometry." Storyboard.SetTargetName(myRectAnimation, spriteName); Storyboard.SetTargetProperty( myRectAnimation, new PropertyPath(RectangleGeometry.RectProperty)); Storyboard ellipseStoryboard = new Storyboard(); ellipseStoryboard.Children.Add(myRectAnimation); myPath.Loaded += delegate(object sender, RoutedEventArgs e) { ellipseStoryboard.Begin(frameworkElement); }; return(myPath); }
public RectAnimationExample() { // Create a NameScope for this page so that // Storyboards can be used. NameScope.SetNameScope(this, new NameScope()); RectangleGeometry myRectangleGeometry = new RectangleGeometry(); myRectangleGeometry.Rect = new Rect(0, 200, 100, 100); // Assign the geometry a name so that // it can be targeted by a Storyboard. this.RegisterName( "MyAnimatedRectangleGeometry", myRectangleGeometry); Path myPath = new Path(); myPath.Fill = Brushes.LemonChiffon; myPath.StrokeThickness = 1; myPath.Stroke = Brushes.Black; myPath.Data = myRectangleGeometry; RectAnimation myRectAnimation = new RectAnimation(); myRectAnimation.Duration = TimeSpan.FromSeconds(2); myRectAnimation.FillBehavior = FillBehavior.HoldEnd; // Set the animation to repeat forever. myRectAnimation.RepeatBehavior = RepeatBehavior.Forever; // Set the From and To properties of the animation. myRectAnimation.From = new Rect(0, 200, 100, 100); myRectAnimation.To = new Rect(600, 50, 200, 50); // Set the animation to target the Rect property // of the object named "MyAnimatedRectangleGeometry." Storyboard.SetTargetName(myRectAnimation, "MyAnimatedRectangleGeometry"); Storyboard.SetTargetProperty( myRectAnimation, new PropertyPath(RectangleGeometry.RectProperty)); // Create a storyboard to apply the animation. Storyboard ellipseStoryboard = new Storyboard(); ellipseStoryboard.Children.Add(myRectAnimation); // Start the storyboard when the Path loads. myPath.Loaded += delegate(object sender, RoutedEventArgs e) { ellipseStoryboard.Begin(this); }; Canvas containerCanvas = new Canvas(); containerCanvas.Children.Add(myPath); Content = containerCanvas; }
public static RectAnimation Animate(double duration, Rect from, Rect to, int repeatCount = 1, EventHandler updating = null, EventHandler Completed = null, bool autoReverse = false, PowerEase easeFunction = null) { var result = new RectAnimation { From = new Rect?(from), To = new Rect?(to), EasingFunction = checkEase(easeFunction) }; return(Animate <RectAnimation>(result, duration, autoReverse, repeatCount, updating, Completed)); }
private void StartKenBurnsAnimation(Shape elementFadeIn) { ImageBrush brush = (ImageBrush)elementFadeIn.Fill; RectAnimation rectAnimation = new RectAnimation(); rectAnimation.From = _randomRects[_index]; rectAnimation.To = _randomRects[_index + 1]; rectAnimation.Duration = new Duration(TimeSpan.FromSeconds(30)); rectAnimation.AutoReverse = true; rectAnimation.RepeatBehavior = RepeatBehavior.Forever; Timeline.SetDesiredFrameRate(rectAnimation, 20); brush.BeginAnimation(TileBrush.ViewboxProperty, rectAnimation); }
private void OnTabChanged(object sender, SelectionChangedEventArgs e) { Storyboard sb = new Storyboard(); Rect newRect = GetItemRect(); RectAnimation anim = new RectAnimation(_prevRect, newRect, new Duration(TimeSpan.FromMilliseconds(250))); Storyboard.SetTargetProperty(anim, new PropertyPath("ItemRect")); sb.FillBehavior = FillBehavior.Stop; sb.Children.Add(anim); sb.Begin(this); _prevRect = newRect; }
private Border CreateScrollingImage(string path) { var anim = new RectAnimation() { To = new Rect(0, 0, 1, 1), RepeatBehavior = RepeatBehavior.Forever }; Storyboard.SetTargetProperty(anim, new PropertyPath("Background.(ImageBrush.Viewport)")); var imageConverter = new ImageSourceConverter(); return(new Border() { Width = 300, Height = 300, Style = new Style() { TargetType = typeof(Border), Triggers = { new System.Windows.EventTrigger() { RoutedEvent = FrameworkElement.LoadedEvent, Actions = { new BeginStoryboard() { Storyboard = new Storyboard() { Children = { anim } } } } } } }, Background = new ImageBrush() { ImageSource = (ImageSource)imageConverter.ConvertFromString(path), Viewport = new Rect(0, 1, 1, 1), TileMode = TileMode.Tile } }); }
/// <summary> /// Crea la animación de rectángulor sobre un control /// </summary> private void CreateRectangleAnimation(DependencyObject control, Rect?from, Rect to, PropertyPath propertyPath, BrushViewBoxActionModel action) { RectAnimation animation = new RectAnimation(); // Asigna las propiedades From y To de la animación if (from != null) { animation.From = from; } if (to != null) { animation.To = to; } // Asigna las funciones animation.EasingFunction = AssignEasingFuntion(action); // Asigna la animación al storyboard AddAnimationToStoryBoard(control, animation, action, propertyPath); }
private void StartStoryBoard(Rect currentRect, Rect targetRect, double time) { RectAnimation rectAnimation = new RectAnimation(); rectAnimation.Duration = TimeSpan.FromSeconds(time); rectAnimation.FillBehavior = FillBehavior.HoldEnd; rectAnimation.To = targetRect; Storyboard.SetTarget(rectAnimation, this); Storyboard.SetTargetProperty(rectAnimation, new PropertyPath(WindowRectProperty)); Storyboard storyBoard = new Storyboard(); storyBoard.Children.Add(rectAnimation); storyBoard.Begin(this); }
private static void AnimateToPosition(DependencyObject d, Rect desiredPosition) { var position = GetPosition(d); if (double.IsNaN(position.X)) { SetPosition(d, desiredPosition); return; } var distance = Math.Max( (desiredPosition.TopLeft - position.TopLeft).Length, (desiredPosition.BottomRight - position.BottomRight).Length); var animationTime = TimeSpan.FromMilliseconds(700);//distance * 2); var animation = new RectAnimation(position, desiredPosition, new Duration(animationTime)); animation.DecelerationRatio = 1; ((UIElement)d).BeginAnimation(PositionProperty, animation); }
private void UpdateChildren(bool useAnimation) { var targetX = (CurrentIndex - 1) * DesiredSize.Width; var targetY = (CurrentIndex - 1) * DesiredSize.Height; var targetPositionOffset = new Rect(targetX, targetY, 0, 0); if (!IsLoaded || !useAnimation || AnimationDuration.TotalMilliseconds == 0) { PositionOffset = targetPositionOffset; } else { var animation = new RectAnimation() { To = targetPositionOffset, Duration = AnimationDuration, EasingFunction = AnimationUtils.CreateEasingFunction(AnimationEase), }; BeginAnimation(PositionOffsetProperty, animation); } }
private void RotateAnimationExample() { var transformGroup = new TransformGroup(); RectAnimation myRectAnimation = new RectAnimation { Duration = TimeSpan.FromSeconds(2), FillBehavior = FillBehavior.HoldEnd, // Set the animation to repeat forever. RepeatBehavior = RepeatBehavior.Forever, // Set the From and To properties of the animation. From = new Rect(0, 0, 100, 100), To = new Rect(0, this.MainGrid.ActualHeight, 200, 50) }; TranslateTransform myTranslateTransform = new TranslateTransform(); Snowflake01.RenderTransform = myTranslateTransform; //Control Rotation speed DoubleAnimation da = new DoubleAnimation { From = 0, To = 360, Duration = new Duration(TimeSpan.FromMilliseconds(2000)), RepeatBehavior = RepeatBehavior.Forever }; RotateTransform myRotateTransform = new RotateTransform { CenterX = Snowflake01.Width / 2, CenterY = Snowflake01.Height / 2 }; transformGroup.Children.Add(myRotateTransform); Snowflake01.RenderTransform = transformGroup; myRotateTransform.BeginAnimation(RotateTransform.AngleProperty, da); }
public static void BeginAnimation <PropertyType>(this IAnimatable animatable, DependencyProperty dp, PropertyType from, PropertyType to, double durationMs) { DependencyObject animation; var duration = TimeSpan.FromMilliseconds(durationMs); switch (to) { case int toInt: var fromInt = (int)Convert.ChangeType(from, typeof(int)); animation = new Int32Animation(fromInt, toInt, duration); break; case double toDouble: var fromDouble = (double)Convert.ChangeType(from, typeof(double)); animation = new DoubleAnimation(fromDouble, toDouble, duration); break; case Color toColor: var fromColor = (Color)Convert.ChangeType(from, typeof(Color)); animation = new ColorAnimation(fromColor, toColor, duration); break; case Thickness toThickness: var fromThickness = (Thickness)Convert.ChangeType(from, typeof(Thickness)); animation = new ThicknessAnimation(fromThickness, toThickness, duration); break; case Rect toRect: var fromRect = (Rect)Convert.ChangeType(from, typeof(Rect)); animation = new RectAnimation(fromRect, toRect, duration); break; default: throw new NotSupportedException(); } animatable.BeginAnimation(dp, animation as AnimationTimeline); }
private void OnMouseUp(object sender, MouseButtonEventArgs e) { if (isDragging && e.ChangedButton == MouseButton.Left) { isDragging = false; ReleaseMouseCapture(); Point endPointInOutput = e.GetPosition(this); Point endPointInVisible = endPointInOutput.Transform(Viewport.Output, Viewport.Visible); Vector mouseShift = -(endPointInVisible - dragStartPointInVisible); Vector outputShift = endPointInOutput - dragStartPointInOutput; int time = e.Timestamp; int deltaTime = time - dragStartTimestamp; double seconds = deltaTime / 1000.0; // mouse moved short enough and for rather long distance. bool shouldStartAnimation = seconds < 1 && outputShift.Length > 20; if (shouldStartAnimation) { Rect moveTo = Viewport.Visible; moveTo.Offset(mouseShift * 2); //if (dragAnimation == null) { dragAnimation = new RectAnimation(moveTo, TimeSpan.FromSeconds(1)); dragAnimation.DecelerationRatio = 0.2; //} //else { // dragAnimation.To = moveTo; // dragAnimation.Duration = TimeSpan.FromSeconds(1); // AnimationClock clock = dragAnimation.CreateClock(); // clock.Controller.Begin(); //} BeginAnimation(VisibleRectProperty, dragAnimation); shouldApplyAnimation = true; Debug.WriteLine("Starting animation"); } else if (dragAnimation != null) { StopDragAnimation(); } // focusing on LMB click if (endPointInVisible == dragStartPointInVisible) { //Keyboard.Focus(Parent as IInputElement); } } else if (isZooming && e.ChangedButton == MouseButton.Left) { isZooming = false; if (zoomRect.HasValue) { Rect output = Viewport.Output; Point p1 = zoomRect.Value.TopLeft.Transform(output, Viewport.Visible); Point p2 = zoomRect.Value.BottomRight.Transform(output, Viewport.Visible); Rect newVisible = new Rect(p1, p2); Viewport.Visible = newVisible; zoomRect = null; ReleaseMouseCapture(); RemoveSelectionAdorner(); } } }
public void UpdateOverlay() { if (TutorialManager.CurrentTutorial != null && TutorialManager.CurrentTutorial.CurrentStep != null) { RectangleGeometry hole = this.Resources["Hole"] as RectangleGeometry; //FrameworkElement target = HelpOverlyHelper.FindChild(Application.Current.MainWindow, TutorialManager.CurrentTutorial.CurrentStep.TargetElementName); FrameworkElement target = GetElement(null, Application.Current.MainWindow, TutorialManager.CurrentTutorial.CurrentStep.Path, 0); if (target != null) { target.PreviewMouseDown -= previewMouseDown; target.PreviewMouseDown += previewMouseDown; } if (hole != null && target != null) { Point targetTopLeft = target.TranslatePoint(new Point(0, 0), Application.Current.MainWindow); Rect newRect = new Rect(targetTopLeft.X - CUTOUT_MARGIN, targetTopLeft.Y - CUTOUT_MARGIN, target.ActualWidth + CUTOUT_MARGIN * 2, target.ActualHeight + CUTOUT_MARGIN * 2); double topDistance = newRect.Top; double bottomDistance = Application.Current.MainWindow.ActualHeight - newRect.Bottom; double leftDistance = newRect.Left; double rightDistance = Application.Current.MainWindow.ActualWidth - newRect.Right; if (topDistance > bottomDistance && topDistance > leftDistance && topDistance > rightDistance) { TutorialManager.CurrentTutorial.CurrentStep.MessagePlacement = Placement.Above; } if (bottomDistance > topDistance && bottomDistance > leftDistance && bottomDistance > rightDistance) { TutorialManager.CurrentTutorial.CurrentStep.MessagePlacement = Placement.Below; } if (leftDistance > bottomDistance && leftDistance > topDistance && leftDistance > rightDistance) { TutorialManager.CurrentTutorial.CurrentStep.MessagePlacement = Placement.Left; } if (rightDistance > bottomDistance && rightDistance > leftDistance && rightDistance > topDistance) { TutorialManager.CurrentTutorial.CurrentStep.MessagePlacement = Placement.Right; } if (hole.Rect != Rect.Empty || TutorialManager.CurrentTutorial.CurrentStep.ToString() == lastTarget) { RectAnimation rectAnimation = new RectAnimation(newRect, duration); rectAnimation.EasingFunction = new CubicEase() { EasingMode = System.Windows.Media.Animation.EasingMode.EaseInOut }; DoubleAnimation fadeInWaitAnimation = new DoubleAnimation(0, 0, duration); fadeInWaitAnimation.Completed += new EventHandler((o, e) => { DoubleAnimation fadeInFinalAnimation = new DoubleAnimation(0, 1, duration); Message.BeginAnimation(Border.OpacityProperty, fadeInFinalAnimation); Arrow.BeginAnimation(Arrow.OpacityProperty, fadeInFinalAnimation); }); //fadeInAnimation.BeginTime = halfDuration.TimeSpan; hole.BeginAnimation(RectangleGeometry.RectProperty, rectAnimation); Arrow.BeginAnimation(Arrow.OpacityProperty, fadeInWaitAnimation); Message.BeginAnimation(Border.OpacityProperty, fadeInWaitAnimation); } else { hole.Rect = newRect; } MessageTextBox.Text = TutorialManager.CurrentTutorial.CurrentStep.Message; if (TutorialManager.CurrentTutorial.CurrentStep.MessagePlacement == Placement.Right) { double leftPlacement = targetTopLeft.X + target.ActualWidth + CUTOUT_MARGIN; Canvas.SetLeft(MessageContainer, leftPlacement); Canvas.SetRight(MessageContainer, 0); Canvas.SetTop(MessageContainer, 0); Canvas.SetBottom(MessageContainer, 0); var size = Application.Current.MainWindow.ActualWidth - leftPlacement; if (size < 0) { size *= -1; } MessageContainer.Width = size; MessageContainer.Height = Application.Current.MainWindow.ActualHeight; } else if (TutorialManager.CurrentTutorial.CurrentStep.MessagePlacement == Placement.Left) { double rightPlacement = targetTopLeft.X - CUTOUT_MARGIN; Canvas.SetRight(MessageContainer, rightPlacement); Canvas.SetLeft(MessageContainer, 0); Canvas.SetTop(MessageContainer, 0); Canvas.SetBottom(MessageContainer, 0); var size = rightPlacement; if (size < 0) { size *= -1; } MessageContainer.Width = size; MessageContainer.Height = Application.Current.MainWindow.ActualHeight; } else if (TutorialManager.CurrentTutorial.CurrentStep.MessagePlacement == Placement.Above) { double bottomPlacement = targetTopLeft.Y - CUTOUT_MARGIN; Canvas.SetBottom(MessageContainer, bottomPlacement); Canvas.SetLeft(MessageContainer, 0); Canvas.SetRight(MessageContainer, 0); Canvas.SetTop(MessageContainer, 0); var size = bottomPlacement; if (size < 0) { size *= -1; } MessageContainer.Width = Application.Current.MainWindow.ActualWidth; MessageContainer.Height = size; } else if (TutorialManager.CurrentTutorial.CurrentStep.MessagePlacement == Placement.Below) { double topPlacement = targetTopLeft.Y + target.ActualHeight + CUTOUT_MARGIN; Canvas.SetTop(MessageContainer, topPlacement); Canvas.SetLeft(MessageContainer, 0); Canvas.SetRight(MessageContainer, 0); Canvas.SetBottom(MessageContainer, 0); var size = Application.Current.MainWindow.ActualHeight - topPlacement; if (size < 0) { size *= -1; } MessageContainer.Width = Application.Current.MainWindow.ActualWidth; MessageContainer.Height = size; } lastTarget = TutorialManager.CurrentTutorial.CurrentStep.ToString(); } } }
public System.Windows.Shapes.Path DoThing(RectangleGeometry RectangleGeometry, Grid grid, string spriteName, FrameworkElement frameworkElement) { var randomDuration = RandomNumber(1000, 4000); // Assign the geometry a name so that // it can be targeted by a Storyboard. frameworkElement.RegisterName( spriteName, RectangleGeometry); System.Windows.Shapes.Path myPath = new System.Windows.Shapes.Path { Fill = System.Windows.Media.Brushes.AliceBlue }; var fullBitmap = new BitmapImage(new Uri(@"pack://application:,,,/Resources/SnowSprite.png")); Int32Rect croppRect = new Int32Rect(0, 0, _FrameWidth, _FrameHeight); var croppedBitmap = new CroppedBitmap(fullBitmap, croppRect); var mybrush = new ImageBrush(croppedBitmap) { Transform = new TranslateTransform(0, 0), AlignmentX = AlignmentX.Left, AlignmentY = AlignmentY.Top, Stretch = Stretch.Fill }; myPath.Fill = mybrush; myPath.StrokeThickness = 1; myPath.Stroke = System.Windows.Media.Brushes.Black; myPath.Data = RectangleGeometry; RectAnimation myRectAnimation = new RectAnimation { BeginTime = TimeSpan.FromSeconds(RandomNumber()), Duration = TimeSpan.FromMilliseconds(randomDuration), FillBehavior = FillBehavior.HoldEnd, // Set the animation to repeat forever. RepeatBehavior = RepeatBehavior.Forever, // Set the From and To properties of the animation. From = new Rect(_randomStartY, _randomStartX, _FrameWidth, _FrameHeight), To = new Rect(_randomStartY, frameworkElement.ActualHeight, _FrameWidth, _FrameHeight) }; // Set the animation to target the Rect property // of the object named "MyAnimatedRectangleGeometry." Storyboard.SetTargetName(myRectAnimation, spriteName); Storyboard.SetTargetProperty( myRectAnimation, new PropertyPath(RectangleGeometry.RectProperty)); //Control Rotation speed DoubleAnimation da = new DoubleAnimation { From = 0, To = 360, Duration = new Duration(TimeSpan.FromMilliseconds(2000)), RepeatBehavior = RepeatBehavior.Forever }; RotateTransform myRotateTransform = new RotateTransform { CenterX = RectangleGeometry.Rect.Width / 2, CenterY = RectangleGeometry.Rect.Height / 2 }; Storyboard.SetTargetName(da, spriteName); Storyboard.SetTargetProperty( da, new PropertyPath(RectangleGeometry.TransformProperty)); Storyboard ellipseStoryboard = new Storyboard(); ellipseStoryboard.Children.Add(myRectAnimation); myPath.Loaded += delegate(object sender, RoutedEventArgs e) { ellipseStoryboard.Begin(frameworkElement); }; return(myPath); }