Search code examples
c#wpfxamlanimationcoloranimation

How to convert ImageBrush to Color in order to animate Canvas.Background (WPF)


I'm trying to make an animation for the background of my canvas, passing progressively from an already defined background using an ImageBrush (it's an image representing a battle scene) to other ImageBrush that represents the end of the game screen. Both images fill all the canvas background. Is there a converter that allows casting ImageBrush to Color? Or some kind of BrushAnimation?

I have tried this but I get System.InvalidCastException: 'No se puede convertir un objeto de tipo 'System.Windows.Media.ImageBrush' al tipo 'System.Windows.Media.SolidColorBrush'.'

            Brush newColor = miLienzo.Background;
            SolidColorBrush newBrush = (SolidColorBrush)newColor;
            Color myColorFromBrush = newBrush.Color;

            endBrush.ImageSource = new BitmapImage(new Uri("Imagenes/fin.jpg", UriKind.Relative));
            Brush newColor2 = endBrush;
            SolidColorBrush newBrush2 = (SolidColorBrush)newColor2;
            Color myColorFromBrush2 = newBrush2.Color;

            ColorAnimation animation;
            animation = new ColorAnimation();
            animation.From = myColorFromBrush;
            animation.To = myColorFromBrush2;
            animation.Duration = new Duration(TimeSpan.FromSeconds(2));
            miLienzo.Background.BeginAnimation(SolidColorBrush.ColorProperty, animation);

Solution

  • You can't do what you're trying to do.

    Put an image in the canvas and make the parts you intend animating transparent.

    Or

    Trace the static part into a geometry using inkscape and use that to define a shape you similarly place in your canvas.

    Either way the static parts are separate and on top of the background.

    Make the background a solidcolorbrush.

    You can then animate the color in that solidcolorbrush. That'll work.

    One advantage of the shape based approach is that this can also have another solidcolorbrush for fill ( and stroke for that matter ). You could then animate the color of that as well.

    Geometries are also fairly lightweight and shapes are vectors so they scale well.

    Or

    Overlay two images with your two pictures as source. Animate the opacity of one down fromk 1.0 to 0 and the other up from 0 to 1.0 to fade one out and the other in. Probably not exactly what you have in mind but could look cool.