How to translate animation on an image diagonally?

你说的曾经没有我的故事 提交于 2019-12-04 02:17:44

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();
}

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 !

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!