Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Android how to use ObjectAnimator to move to point x along a curve

Tags:

android

I have an image view "stone" and am moving it from its current position to a X,Y position. I want it to move along a curve. Please let me know how I can do that(i have set the min api as 11)

ObjectAnimator moveX = ObjectAnimator.ofFloat(stone, "x", catPos[0] );
ObjectAnimator moveY = ObjectAnimator.ofFloat(stone, "y", catPos[1] );
AnimatorSet as = new AnimatorSet();
as.playTogether(moveX, moveY);
as.start();
like image 416
Aparna Avatar asked Dec 01 '22 14:12

Aparna


1 Answers

The answer by Budius seems perfectly useful to me.

Here are the animator objects I use:

Purpose: Move View "view" along Path "path"

Android v21+:

// Animates view changing x, y along path co-ordinates
ValueAnimator pathAnimator = ObjectAnimator.ofFloat(view, "x", "y", path)

Android v11+:

// Animates a float value from 0 to 1 
ValueAnimator pathAnimator = ValueAnimator.ofFloat(0.0f, 1.0f);

// This listener onAnimationUpdate will be called during every step in the animation
// Gets called every millisecond in my observation  
pathAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

float[] point = new float[2];

@Override
    public void onAnimationUpdate(ValueAnimator animation) {
        // Gets the animated float fraction
        float val = animation.getAnimatedFraction();

        // Gets the point at the fractional path length  
        PathMeasure pathMeasure = new PathMeasure(path, true);
        pathMeasure.getPosTan(pathMeasure.getLength() * val, point, null);

        // Sets view location to the above point
        view.setX(point[0]);
        view.setY(point[1]);
    }
});

Similar to: Android, move bitmap along a path?

like image 122
Dileep P G Avatar answered Dec 10 '22 13:12

Dileep P G