skew animation unable to animate

2019-08-08 20:05发布

问题:

I have made progress on translating my skew animation to the double animation class. The only problem left is when the animation is called by the dispatch timer, an error is thrown. The error is as follows...

Cannot animate the 'AngleX' property on 'System.Windows.Media.MatrixTransform' because the object is sealed or frozen.

How would i overcome this error so that the animation can work?

    public static void Grass(Canvas canvas, int boundry)
    {
        foreach (var element in canvas.Children.OfType<Image>())
        {
            if (element.Name == "GrassForeground" || element.Name == "GrassBackground")
            {
                var skewGrass = new DoubleAnimation
                {
                    From = 0,
                    To = 10,
                    EasingFunction = new BackEase(),
                    AutoReverse = true
                };
                var transform = (MatrixTransform)element.RenderTransform;
                transform.BeginAnimation(SkewTransform.AngleXProperty, skewGrass);
            }
        }
    }

回答1:

Try this below, or do you have a special reason to use MatrixTransform?

public static void Grass(Canvas canvas, int boundry)
{
    foreach (var element in canvas.Children.OfType<Image>())
    {
        if (element.Name == "GrassForeground" || element.Name == "GrassBackground")
        {
            var skewGrass = new DoubleAnimation
            {
                Duration = new Duration(TimeSpan.FromSeconds(5)),
                From = 0,
                To = 10,
                EasingFunction = new BackEase(),
                AutoReverse = true
            };
            element.RenderTransform = new SkewTransform();
            element.RenderTransform.BeginAnimation(SkewTransform.AngleXProperty, skewGrass);
        }
    }
}


回答2:

Your element ALREADY have a RenderTransform property assign, but this object is a frozen SkewTransform object. You can't change it's AngleX property since it is already rendered.

If you assign the RenderTransform property to a new SkewTransform() this SkewTransform won't be frozen an can be animated.

Although the Freezable class has many applications, most Freezable objects in Windows Presentation Foundation (WPF) are related to the graphics sub-system.

Here is a complete explanation : Freezable Objects Overview on MSDN