tmighty
tmighty

Reputation: 11399

Animation doesn't show steps-in-between

I have created a simple function that would "animate" the cell backcolor at a tap, it works perfectly fine:

        Color nOldColor = _grid.BackgroundColor;

        for (int i = 0; i <= 100; i += 5)
        {
            double f = (double)i / (double)100;
            Color nNewColor = PCLHelper.BlendColors(nOldColor, Color.Red, f);
            _grid.BackgroundColor = nNewColor;
            _label1.BackgroundColor = nNewColor;
            await Task.Delay(5);
        }
        _grid.BackgroundColor = nOldColor;
        _label1.BackgroundColor = nOldColor;

Now I wanted to do the same with an Animation, but the animation doesn't show the steps "in-between" but rather (as it looks to me) switches to the final color:

    private async void animateButtonTouched()
    {

        int repeatCountMax = 100;
        Color nOldColor = _grid.BackgroundColor;

        var repeatCount = 0;
        _grid.Animate("changeBG", new Animation((val) =>
        {
            double f = (double)repeatCount / (double)100;
            Color nNewColor = PCLHelper.BlendColors(nOldColor, Color.Red, f);
            _grid.BackgroundColor = nNewColor;
            _label1.BackgroundColor = nNewColor;
        }),
        5, //duration. I've also tried it with 100. Nothing helped
        finished: (val, b) =>
        {
            repeatCount++;
        }, repeat: () =>
        {
            return repeatCount < repeatCountMax;
        });

What am I doing wrong?

Upvotes: 2

Views: 47

Answers (1)

SushiHangover
SushiHangover

Reputation: 74134

"You are making it more difficult than it needs to be." Trademark pending 🍣

The Animate callback is providing the stepping value (or keyframe value). This is a double from 0 to 1 that is called ever X milliseconds (i.e. the length of a single animation frame, 16 default) over the course of X milliseconds (250 default).

So in this example the ShiftToColor gets called 125 times (2000 / 16) with a value that is evenly divided from 0 to 1, thus steps of .008.

var orgColor = aFormsElementInstance.BackgroundColor;
aFormsElementInstance.Animate("changeBG", new Animation((val) =>
{
    Color ShiftToColor(Color From, Color To, double pct)
    {
        var r = From.R + ((To.R - From.R) * val);
        var g = From.G + ((To.G - From.G) * val);
        var b = From.B + ((To.B - From.B) * val);
        return new Color(r, g, b);
    }
    Device.BeginInvokeOnMainThread(() =>
    {
        aFormsElementInstance.BackgroundColor = ShiftToColor(orgColor, Color.Red, val);
    });
}), 16, 2000);

Results in:

enter image description here

Upvotes: 1

Related Questions