Android中属性动画5----ValueAnimator.ofObject的使用

作用:ValueAnimator.ofObject(TypeEvaluator evaluator, Object… values)方法,是用于对任意对象进行动画操作的。但是相比于浮点型或整型数据(https://blog.csdn.net/zhaihaohao1/article/details/78584822),对象的动画操作明显要更复杂一些。我们先谈一下基本用法

1首先定义一个MyPoint类存放坐标

package com.zhh.myapplication.test6;

/**
 * Created by 16838 on 2018/7/6.
 */
public class MyPoint {

    private float x;

    private float y;

    public MyPoint(float x, float y) {
        this.x = x;
        this.y = y;
    }

    public float getX() {
        return x;
    }

    public float getY() {
        return y;
    }
}

2估值器TypeEvaluator
产生从动画开始到结束的所有坐标值

package com.zhh.myapplication.test6;

import android.animation.TypeEvaluator;
import android.graphics.Point;

/**
 *估值器
 * Created by 16838 on 2018/7/6.
 */
public class MyPointEvaluator implements TypeEvaluator {
//  evaluate()方法当中传入了三个参数,
// fraction完成度动画完成度
// startValue开始坐标
// endValue结束坐标
    @Override
    public Object evaluate(float fraction, Object startValue, Object endValue) {
        MyPoint startPoint = (MyPoint) startValue;
        MyPoint endPoint = (MyPoint) endValue;
//      计算出画一条直线需要的所坐标(这里只是一个公式)
        float mX = startPoint.getX() + fraction * (endPoint.getX() - startPoint.getX());
        float mY = startPoint.getY() + fraction * (endPoint.getY() - startPoint.getY());
        MyPoint point = new MyPoint(mX, mY);
        return point;
    }

}

3通过ValueAnimator拿到动画所需要的所有坐标值

 private void myValueAnimator() {
//      起点坐标
        MyPoint point1 = new MyPoint(0, 0);
//      终点坐标
        MyPoint point2 = new MyPoint(1, 1);
//      .ofObject传入估值器和起始坐标
        ValueAnimator anim = ValueAnimator.ofObject(new MyPointEvaluator(), point1, point2);
//      时长
        anim.setDuration(100);
//      开始
        anim.start();
//      动画监听事件
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                MyPoint myPoint = (MyPoint) animation.getAnimatedValue();
//              打印出(0, 0)到(1, 1)之间的小数
                Log.e("111", "x>>>" + myPoint.getX() + "y>>>" + myPoint.getY());

//                打印结果
//                x>>>0.0y>>>0.0
//                x>>>0.069628954y>>>0.069628954
//                x>>>0.24547935y>>>0.24547935
//                x>>>0.7545208y>>>0.7545208
//                x>>>0.9303709y>>>0.9303709
//                x>>>1.0y>>>1.0
            }
        });
    }

4拿到坐标值就可以结合自定义控件绘制出一条直线运动(下一篇再讲)

源码下载
TestLayout—–动画
https://download.csdn.net/download/zhaihaohao1/10525191

你可能感兴趣的:(动画)