How to translate animation on an image diagonally?

2020-07-06 05:40发布

问题:

I want to animate an image diagonally like below picture. I have tried translate animation but I am only able to do it either parallel X-axis or parallel Y-axis.

But couldn't able to figure out how to do it diagonally. And I am also not sure it can be done by translate animation or some other kinda animation. So please suggest me how can I do it or if any one can give me a helpful link then also I will be obiliged.

回答1:

One way is to use an AnimatorSet to play more ObjectAnimator together.

private void animateDiagonalPan(View v) {
    AnimatorSet animSetXY = new AnimatorSet();

    ObjectAnimator y = ObjectAnimator.ofFloat(v,
                "translationY",v.getY(), targetY);

    ObjectAnimator x = ObjectAnimator.ofFloat(v,
                "translationX", v.getX(), targetX);

    animSetXY.playTogether(x, y);
    animSetXY.setInterpolator(new LinearInterpolator(1f));
    animSetXY.setDuration(300);
    animSetXY.start();
}

Or you could use a custom View with a custom Property, but in this case you will need to compute translation on X and Y yourself:

final Property<YourView, Float> transProperty = new Property<YourView, Float>(
        float.class, "translation") {
    @Override
    public Float get(YourView) {
        return object.getTranslation();
    }

    @Override
    public void set(YourView, Float value) {
        object.translate(value);
    }
};

private void translate(float value){
       setTranslationX(value);
       setTranslationY(value);
}

And use it to animate:

private void animateDiagonalPan(View v) {

    ObjectAnimator xy = ObjectAnimator.ofFloat(v,
                transProperty, targetValue);

    xy.setInterpolator(new LinearInterpolator(1f));
    xy.setDuration(300);
    xy.start();
}


回答2:

You can achieve this with just one ObjectAnimator.

ObjectAnimator centerChangeAnim = ObjectAnimator.ofObject(this, "centerpoint", new PointEvaluator(), fromPoint, toPoint);
centerChangeAnim.start()

And in the same class add the callback function.

public void setCenterpoint(Point centerPoint) {
    this.circleCenter = centerPoint;
  }

And here is the customtype evaluator that combines X and Y.

public class PointEvaluator implements TypeEvaluator<Point> {
    @Override
    public Point evaluate(float t, Point startPoint, Point endPoint) {
        int x = (int) (startPoint.x + t * (endPoint.x - startPoint.x));
        int y = (int) (startPoint.y + t * (endPoint.y - startPoint.y));
        return new Point(x,y);
    }
}

Enjoy !