简体   繁体   English

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

[英]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.我正在尝试使用代码隐藏中的StoryBoard同时为RectangleTranslateTransformScaleTransform设置动画。 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),
        };
    }

In XAML, give your rectangle a TransformGroup:在 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>

In the code-behind, use the BeginAnimation method on the transforms:在代码隐藏中,对转换使用 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM