它使用DoubleAnimationUsingKeyFrames无效

时间:2014-03-07 10:44:22

标签: c# wpf

我想使用DoubleAnimationUsingKeyFrames制作动画来转动矩形。但我无法弄清楚为什么它不起作用。

        rect.RenderTransformOrigin = new Point(0.5, 0.5);

        TransformGroup myTransformGroup = new TransformGroup();
        ScaleTransform myScaleTransform = new ScaleTransform();
        myTransformGroup.Children.Add(myScaleTransform);

        rect.RenderTransform = myTransformGroup;

        DoubleAnimationUsingKeyFrames myDoubleAnimationUsingKeyFrames = new DoubleAnimationUsingKeyFrames();
        myDoubleAnimationUsingKeyFrames.Duration = TimeSpan.FromSeconds(3);

        EasingDoubleKeyFrame myEasingDoubleKeyFrame = new EasingDoubleKeyFrame();
        myEasingDoubleKeyFrame.KeyTime = TimeSpan.FromSeconds(0);
        myEasingDoubleKeyFrame.Value = -1;
        myEasingDoubleKeyFrame.KeyTime = TimeSpan.FromSeconds(3);
        myEasingDoubleKeyFrame.Value = 1;
        myEasingDoubleKeyFrame.EasingFunction = new CubicEase()
        {
            EasingMode = EasingMode.EaseOut
        };

        myDoubleAnimationUsingKeyFrames.KeyFrames.Add(myEasingDoubleKeyFrame);

        Storyboard.SetTarget(myDoubleAnimationUsingKeyFrames, rect);
        Storyboard.SetTargetProperty(myDoubleAnimationUsingKeyFrames, new PropertyPath("RenderTransform.Children[0].ScaleX"));

        Storyboard myStoryboard = new Storyboard();
        myStoryboard.Children.Add(myDoubleAnimationUsingKeyFrames);
        myStoryboard.Begin();

XAML文件是:

<Grid>
    <Rectangle x:Name="rect"  Width="200" Height="100"  Fill="Black"></Rectangle>
</Grid>

1 个答案:

答案 0 :(得分:1)

使用常规的DoubleAnimation。那么你不需要比这更多的代码:

var transform = new ScaleTransform();
var animation = new DoubleAnimation
{
    From = -1,
    Duration = TimeSpan.FromSeconds(3),
    EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }
};

rect.RenderTransformOrigin = new Point(0.5, 0.5);
rect.RenderTransform = transform;

transform.BeginAnimation(ScaleTransform.ScaleXProperty, animation);

您还可以在XAML中设置RenderTransformRenderTransformOrigin属性:

<Rectangle x:Name="rect" Width="200" Height="100" Fill="Black"
           RenderTransformOrigin="0.5,0.5">
    <Rectangle.RenderTransform>
        <ScaleTransform/>
    </Rectangle.RenderTransform>
</Rectangle>

然后你的代码减少到:

rect.RenderTransform.BeginAnimation(ScaleTransform.ScaleXProperty,
    new DoubleAnimation
    {
        From = -1,
        Duration = TimeSpan.FromSeconds(3),
        EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }
    });