How to animate TranslateTransform and ScaleTransform in WPF
I am trying to animate in TranslateTransform
and ScaleTransform
out Rectangle
at the same time using StoryBoard
an encoding. I've looked into some similar questions, but I'm like I'm still stuck with the first step.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Rectangle x:Name="MyRectangle" Width="100" Height="100" Fill="Aqua"></Rectangle>
<Button Grid.Row="1" Content="Animate" Click="ButtonBase_OnClick"/>
</Grid>
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var translate_x = new DoubleAnimation()
{
From = 0,
To = 100,
Duration = TimeSpan.FromSeconds(5),
};
var translate_y = new DoubleAnimation()
{
From = 0,
To = 100,
Duration = TimeSpan.FromSeconds(5),
};
var scale_x = new DoubleAnimation()
{
From = 1,
To = 2,
Duration = TimeSpan.FromSeconds(5),
};
var scale_y = new DoubleAnimation()
{
From = 1,
To = 2,
Duration = TimeSpan.FromSeconds(5),
};
}
+3
source to share
1 answer
In XAML, give your rectangle a TransformGroup:
<Rectangle x:Name="MyRectangle" Width="100" Height="100" Fill="Chartreuse">
<Rectangle.RenderTransform>
<TransformGroup>
<ScaleTransform x:Name="rectScale"/>
<TranslateTransform x:Name="rectTrans"/>
</TransformGroup>
</Rectangle.RenderTransform>
</Rectangle>
In your code, use the BeginAnimation method for transformations:
rectScale.BeginAnimation(ScaleTransform.ScaleXProperty, scale_x);
rectScale.BeginAnimation(ScaleTransform.ScaleYProperty, scale_y);
rectTrans.BeginAnimation(TranslateTransform.XProperty, translate_x);
rectTrans.BeginAnimation(TranslateTransform.YProperty, translate_y);
+5
source to share