Search code examples
c#animationuwpoffset

How to set offset to SpringVector3NaturalMotionAnimation?


How to set the offset point for SpringVector3NaturalMotionAnimation? Using following code the animation works well except I cannot set the offset point to middle of the FrameworkElement. Now the offset is at the left-upper corner.

       private static void ScaleAnimation_Internal(FrameworkElement TargetFrameworkElement, int ScaleInProsents, TimeSpan Duration, TimeSpan Delay, int DampingRatioProsent)
        {
            AnimationClass TargetAnimationClass = AddScaleAnimation(TargetFrameworkElement);
            Compositor TargetCompositor = Window.Current.Compositor;
            //UPDATE
            TargetAnimationClass.TargetSpringVector3NaturalMotionAnimation.FinalValue = new Vector3((float)ScaleInProsents / 100);
            if (Duration != TimeSpan.Zero) TargetAnimationClass.TargetSpringVector3NaturalMotionAnimation.Period = Duration;
            if (Delay != TimeSpan.Zero) TargetAnimationClass.TargetSpringVector3NaturalMotionAnimation.DelayTime = Delay;
            if (DampingRatioProsent >= 0) TargetAnimationClass.TargetSpringVector3NaturalMotionAnimation.DampingRatio = (float)DampingRatioProsent / 100;
            //START ANIMATION
            TargetFrameworkElement.StartAnimation(TargetAnimationClass.TargetSpringVector3NaturalMotionAnimation);
        }

Solution

  • As @Johnny Westlake said, you just need set the CenterPoint before StartAnimation invoked. For example

    Compositor _compositor = Window.Current.Compositor;
    SpringVector3NaturalMotionAnimation _springAnimation;
    
    private void Btn_PointerEntered(object sender, PointerRoutedEventArgs e)
    {
        CreateOrUpdateSpringAnimation(1.5f);
        (sender as UIElement).CenterPoint = new Vector3((float)(Btn.ActualWidth / 2.0), (float)(Btn.ActualHeight / 2.0), 1f);
        (sender as UIElement).StartAnimation(_springAnimation);
    
    }
    
    private void Btn_PointerExited(object sender, PointerRoutedEventArgs e)
    {
        CreateOrUpdateSpringAnimation(1.0f);
        (sender as UIElement).CenterPoint = new Vector3((float)(Btn.ActualWidth / 2.0), (float)(Btn.ActualHeight / 2.0), 1f);
        (sender as UIElement).StartAnimation(_springAnimation);
    
    
    }
    private void CreateOrUpdateSpringAnimation(float finalValue)
    {
        if (_springAnimation == null)
        {
            _springAnimation = _compositor.CreateSpringVector3Animation();
            _springAnimation.Target = "Scale";
    
        }
    
        _springAnimation.FinalValue = new Vector3(finalValue);
    }
    

    Xaml Code

    <Grid>
        <Button Name="Btn" Content="ClickMe" 
                PointerEntered="Btn_PointerEntered"
                PointerExited="Btn_PointerExited"
               VerticalAlignment="Center" HorizontalAlignment="Center" >
    
        </Button>
    </Grid>