如何在 WPF 中为 TranslateTransform 和 ScaleTransform 设置动画

How to animate TranslateTransform and ScaleTransform in WPF

我正在尝试使用代码隐藏中的 StoryBoard 同时为 RectangleTranslateTransformScaleTransform 设置动画。我研究了一些类似的问题,但我仍然停留在第一步。

<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),
        };
    }

在 XAML 中,给你的矩形一个 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>

在代码隐藏中,对变换使用 BeginAnimation 方法:

rectScale.BeginAnimation(ScaleTransform.ScaleXProperty, scale_x);
rectScale.BeginAnimation(ScaleTransform.ScaleYProperty, scale_y);
rectTrans.BeginAnimation(TranslateTransform.XProperty, translate_x);
rectTrans.BeginAnimation(TranslateTransform.YProperty, translate_y);

如果rectScale.BeginAnimation()不行试试 rectScale.RenderTransform.BeginAnimation(ScaleTransform.ScaleXProperty, scale_x);