自定义View | ofObject详解与实战(ValueAnimator进阶)

  • 2019 年 10 月 8 日
  • 筆記
  • ofInt()ofFloat()函数用来定义动画, 但ofInt()函数只能传入Integer类型的值, ofFloat()函数则只能传入Float类型的值。
  • 如果需要操作其他类型的变量, 需要使用ValueAnimator另一个函数ofObject(), 可以传入任何类型的变量。
  • Ctrl + 左键看一下源码对ofObject()的定义
    public static ValueAnimator ofObject(TypeEvaluator evaluator, Object... values) {          ValueAnimator anim = new ValueAnimator();          anim.setObjectValues(values);          anim.setEvaluator(evaluator);          return anim;      }
  • 第一个参数是自定义Evaluator; 第二个参数是可变长参数,属于Object类型;
  • 第一个参数Evaluator的作用: 根据当前动画的数值进度计算出当前进度所对应的值。 既然Object对象是我们自定义的, 那必然从进度到值的转换过程也必须由我们来做, 否则系统不可能知道我们要将数值进度转换成什么具体值
  • 使用ofObject()函数实现将TextView的内容从字母A变化到Z
    private void startAnimationTestCharEvaluator() {          ValueAnimator animator = ValueAnimator.ofObject(new CharEvaluator(), 'A', 'Z');            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {              @Override              public void onAnimationUpdate(ValueAnimator animation) {                  char text = (Character) animation.getAnimatedValue();                  tv_text.setText(String.valueOf(text));              }          });          animator.setDuration(10000);          animator.setInterpolator(new AccelerateInterpolator());          animator.start();      }
这里注意两个地方
  • 第一,构造ValueAnimator时,传入了一个自定义CharEvaluator; 在初始化动画时,传入的是Character对象 字母A字母Z 在这里要实现的效果是: 对Character对象应用动画, 动画自动将字母A变化到字母Z具体实现则封装CharEvaluator中, 这里只需知道, 构造ValueAnimator时传入的是两个Character对象, 一个是起始值,另一个是终止值,即可。
  • 第二,监听; !!!构造类型返回值类型相一致!!! 先通过animation.getAnimatedValue()函数得到当前动画的字符, 然后把字符设置给TextView构造ValueAnimator时, 传入的值类型Character对象 所以 在动画过程中通过Evaluator 返回的值类型 必然跟构造时的类型一致的 也是Character对象。

ASCII码表中数字与字符的转换方法

  • ASCII码表中,每个字符都有数字与它一一对应, 字母A~Z之间的所有字母对应的数字区间为65~90
  • 在程序中,可以数字强制转换成对应的字符
  • 数字转字符 char temp =(char)65;//得到的 temp的值 就是 大写字母A
  • 字符转数字 char temp = 'A'; int num = (int) temp; //这里得到的num值就是对应的ASCII码值65
实现CharEvaluator
public class CharEvaluator implements TypeEvaluator<Character> {        @Override      public Character evaluate(float fraction, Character startValue, Character endValue) {          int startInt = (int)startValue;          int endInt = (int)endValue;          int curInt = (int) (startInt + fraction * (endInt - startInt));            char result = (char) curInt;            return result;      }    }
  • 先把Character对象转换成Int去运算, 再把运算完的Int结果转换成Character返回

案例:抛物动画

插值器只能改变动画进展的快慢, 而Evaluator则可以改变返回的值。 Evaluator与ofObject结合 使得ValueAnimator更加强大 使参数可以在Evaluator中处理, 并返回给一个自定义的对象

  • 下面实现一个抛物动画, 当单击按钮时,圆球开始向下做抛物运动, 在滚动一段距离后结束;
实现(FallingBallActivity)

1.利用shape标签实现一个圆形Drawable(drawable/circle.xml)

<?xml version="1.0" encoding="utf-8"?>  <shape xmlns:android="http://schemas.android.com/apk/res/android"      android:shape='oval'>        <solid android:color="#0066FF"/>    </shape>

2.FallingBallActivity布局文件

<?xml version="1.0" encoding="utf-8"?>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:app="http://schemas.android.com/apk/res-auto"      xmlns:tools="http://schemas.android.com/tools"      android:orientation="horizontal"      android:layout_width="match_parent"      android:layout_height="match_parent"      tools:context=".CustomViews.FallingBallActivity">        <ImageView          android:id="@+id/ball_img"          android:layout_width="50dp"          android:layout_height="50dp"          android:src="@drawable/circle"/>        <Button          android:id="@+id/start_fallingBallAnim"          android:text="StartAnim"          android:layout_width="wrap_content"          android:layout_height="wrap_content" />    </LinearLayout>
  1. Activity代码 核心在于button的点击事件, 注意代码中注释:

这里需要定义球的位置, 需要实时计算出当前球所在的 X,Y 坐标, 所以ValueAnimator要返回含有X,Y坐标的对象 才能将球移动到指定位置; 这里使用Point对象来返回球在每一时刻的位置

public class FallingBallActivity extends AppCompatActivity {        private Button startAnim;      private ImageView ballImg;        @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_falling_ball);            initViews();      }        private void initViews() {          startAnim = findViewById(R.id.start_fallingBallAnim);          ballImg = findViewById(R.id.ball_img);            startAnim.setOnClickListener(new View.OnClickListener() {              @Override              public void onClick(View v) {                    //设置自定义Evaluator, 以及初始值终止值(皆为Point类型)                  ValueAnimator animator = ValueAnimator.ofObject(new FallingBallEvaluator(),                          new Point(0, 0), new Point(500, 500));                    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {                      @Override                      public void onAnimationUpdate(ValueAnimator animation) {                          Point mCurPoint = (Point) animation.getAnimatedValue();                            //以函数x,y值为左上坐标,加以自身宽高为右下坐标                          ballImg.layout(mCurPoint.x, mCurPoint.y, mCurPoint.x + ballImg.getWidth(),                                  mCurPoint.y + ballImg.getHeight());                      }                  });                  animator.setDuration(2000);                  animator.start();              }          });      }  }
  1. 最重要的FallingBallEvaluator, 由它返回每一时刻球的实际位置。
public class FallingBallEvaluator implements TypeEvaluator<Point> {        private Point point = new Point();        @Override      public Point evaluate(float fraction, Point startValue, Point endValue) {          point.x = (int) (startValue.x + fraction * (endValue.x - startValue.x));            //y为二倍速          if (fraction * 2 <= 1) {                //y二倍速,若未完成,继续二倍刷新              point.y = (int) (startValue.y + fraction * 2 * (endValue.y - startValue.y));          } else {              //如果完成,则不变              point.y = endValue.y;          }            return point;      }  }

计算point,把x、y值分开来算

  • x值的运算结果赋给结果point对象的x, y值的运算结果赋给结果point对象的y, 即可
  • 在抛物运动中, 物体在X轴方向的速度是不变的,所以在X轴方向它的实时位置是: point.x=(int)(startValue.x+fraction*(endValue.x-startValue.x)); 而在Y轴方向则是s=V0t+gt*t。 其中,V0表示初始速度; g是重力加速度,取值是9.8;t表示当前的时间。
  • 而在这里我们是没有时间概念的,只有fraction表示的进度, 所以要想完美匹配这个自由落体公式, 需要复杂的计算,这不是本例的重点。
  • 这里取一个折中公式:将实时进度乘以2作为当前进度。 很显然,Y轴的进度会首先完成(变成1), 这时X轴还是会继续前进的, 所以在视觉上会产生落地后继续滚动的效果。