如何在WPF中为TranslateTransform和ScaleTransform设置动画 [英] How to animate TranslateTransform and ScaleTransform in WPF

查看:237
本文介绍了如何在WPF中为TranslateTransform和ScaleTransform设置动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在代码后面使用StoryBoardRectangleTranslateTransformScaleTransform设置动画.我研究了一些类似的问题,但我仍然对第一步感到困惑.

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

推荐答案

在XAML中,为矩形提供一个TransformGroup:

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>

在后面的代码中,对转换使用BeginAnimation方法:

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

这篇关于如何在WPF中为TranslateTransform和ScaleTransform设置动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆