Reputation: 13
I want to make a animation using DoubleAnimationUsingKeyFrames to turn a rectangle. But I can't figure out why it doesn't work.
rect.RenderTransformOrigin = new Point(0.5, 0.5);
TransformGroup myTransformGroup = new TransformGroup();
ScaleTransform myScaleTransform = new ScaleTransform();
myTransformGroup.Children.Add(myScaleTransform);
rect.RenderTransform = myTransformGroup;
DoubleAnimationUsingKeyFrames myDoubleAnimationUsingKeyFrames = new DoubleAnimationUsingKeyFrames();
myDoubleAnimationUsingKeyFrames.Duration = TimeSpan.FromSeconds(3);
EasingDoubleKeyFrame myEasingDoubleKeyFrame = new EasingDoubleKeyFrame();
myEasingDoubleKeyFrame.KeyTime = TimeSpan.FromSeconds(0);
myEasingDoubleKeyFrame.Value = -1;
myEasingDoubleKeyFrame.KeyTime = TimeSpan.FromSeconds(3);
myEasingDoubleKeyFrame.Value = 1;
myEasingDoubleKeyFrame.EasingFunction = new CubicEase()
{
EasingMode = EasingMode.EaseOut
};
myDoubleAnimationUsingKeyFrames.KeyFrames.Add(myEasingDoubleKeyFrame);
Storyboard.SetTarget(myDoubleAnimationUsingKeyFrames, rect);
Storyboard.SetTargetProperty(myDoubleAnimationUsingKeyFrames, new PropertyPath("RenderTransform.Children[0].ScaleX"));
Storyboard myStoryboard = new Storyboard();
myStoryboard.Children.Add(myDoubleAnimationUsingKeyFrames);
myStoryboard.Begin();
The XAML file is:
<Grid>
<Rectangle x:Name="rect" Width="200" Height="100" Fill="Black"></Rectangle>
</Grid>
Upvotes: 0
Views: 572
Reputation: 128061
Use a regular DoubleAnimation. Then you don't need more code than this:
var transform = new ScaleTransform();
var animation = new DoubleAnimation
{
From = -1,
Duration = TimeSpan.FromSeconds(3),
EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }
};
rect.RenderTransformOrigin = new Point(0.5, 0.5);
rect.RenderTransform = transform;
transform.BeginAnimation(ScaleTransform.ScaleXProperty, animation);
You might also set the RenderTransform
and RenderTransformOrigin
properties in XAML:
<Rectangle x:Name="rect" Width="200" Height="100" Fill="Black"
RenderTransformOrigin="0.5,0.5">
<Rectangle.RenderTransform>
<ScaleTransform/>
</Rectangle.RenderTransform>
</Rectangle>
Then your code reduces to this:
rect.RenderTransform.BeginAnimation(ScaleTransform.ScaleXProperty,
new DoubleAnimation
{
From = -1,
Duration = TimeSpan.FromSeconds(3),
EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }
});
Upvotes: 1