Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to animate TranslateTransform and ScaleTransform in WPF

I'm trying to animate the TranslateTransform and ScaleTransform of a Rectangle at the same time using a StoryBoard in code-behind. I studied some similar questions but I some how I'm still stuck at 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),
        };
    }
like image 488
Vahid Avatar asked Mar 15 '23 08:03

Vahid


1 Answers

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 the code-behind, use the BeginAnimation method on the transforms:

rectScale.BeginAnimation(ScaleTransform.ScaleXProperty, scale_x);
rectScale.BeginAnimation(ScaleTransform.ScaleYProperty, scale_y);
rectTrans.BeginAnimation(TranslateTransform.XProperty, translate_x);
rectTrans.BeginAnimation(TranslateTransform.YProperty, translate_y);
like image 67
tsandy Avatar answered Mar 23 '23 06:03

tsandy