How to apply Image TranslateTranform to an Image by step (Jump a few Pixel)

825 Views Asked by At

I currently using the TranslateTransform on an image by code in my App and it's working correctly.

But I would like the image to move by step, let's say jump 10 or 20 pixel on each movement. Is there a way to do this. This to give a retro flavor to the movement.

I was thinking something like TranslateTransform.Step = 10;

            Duration durationX = new TimeSpan(0, 0, 0, 0, 600);
            Duration durationY = new TimeSpan(0, 0, 0, 0, 400);

            DoubleAnimation moveX = new DoubleAnimation();
            moveX.Duration = durationX;
            moveX.To = ((ImgCanvasCoordinates[cardSource][0] - ImgCanvasCoordinates[cardTarget][0]) * -1);
            DoubleAnimation moveY = new DoubleAnimation();
            moveY.Duration = durationY;
            moveY.To = ((ImgCanvasCoordinates[cardSource][1] - ImgCanvasCoordinates[cardTarget][1]) * -1);

            Storyboard story1 = new Storyboard();
            story1.Children.Add(moveX);
            story1.Children.Add(moveY);
            Storyboard.SetTarget(moveX, imgGhost);
            Storyboard.SetTarget(moveY, imgGhost);
            Storyboard.SetTargetProperty(moveX, "(Image.RenderTransform).(TranslateTransform.X)");
            Storyboard.SetTargetProperty(moveY, "(Image.RenderTransform).(TranslateTransform.Y)");

            story1.Begin();
1

There are 1 best solutions below

5
walterlv On BEST ANSWER

Preview of the step animating effect

You can use a custom EasingFunction to achieve this.

By writing an EasingFunction you can fully control the movement of animation. I've written a StepEasingFunction as shown below:

public class StepEasingFunction : EasingFunctionBase
{
    public double NormalizedStep { get; set; }

    protected override Freezable CreateInstanceCore()
    {
        return new StepEasingFunction {NormalizedStep = NormalizedStep};
    }

    protected override double EaseInCore(double normalizedTime)
    {
        var stepIndex = Math.Round(normalizedTime / NormalizedStep);
        return NormalizedStep * stepIndex;
    }
}

Then, just add an EasingFunction assigning to the animations:

moveX.EasingFunction = new StepEasingFunction {NormalizedStep = 0.2};
moveY.EasingFunction = new StepEasingFunction {NormalizedStep = 0.2};

Then, how to calculate the value of the NormalizedStep property?

You said that you want a 10-pixel movement for each step, so calculate the step total count and use 1 / stepTotalCount to calculate the final NormalizedStep property.