Android实现抛物线小球

关于二阶贝塞尔曲线的方程  详见 Android自定义控件实战——水流波动效果的实现WaveView

主要思路就是通过 ValueAnimator 进行动画设置。

 

 ValueAnimator代码

 1  public void initValueAnimator(){
 2         //
 3         valueAnimator = new ValueAnimator();
 4         //初始化起始坐标和结束坐标
 5         valueAnimator.setObjectValues(new PointF(mStart.x, mStart.y), new PointF(mEnd.x, mEnd.y));
 6         //设置自定义动画估值器
 7         valueAnimator.setEvaluator(new BezierEvaluator());
 8         valueAnimator.setDuration(mDefaultDuration);
 9         //
10         valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
11             @Override
12             public void onAnimationUpdate(ValueAnimator animation) {
13                 //更新坐标
14                 PointF pointF = (PointF) animation.getAnimatedValue();
15                 layoutParams.x = (int) pointF.x;
16                 layoutParams.y = (int) pointF.y;
17                 windowManager.updateViewLayout(mView,layoutParams);
18             }
19         });
20         //
21         valueAnimator.setTarget(windowManager);
22         valueAnimator.setRepeatCount(mRepeatCount);
23     }

实现自定义估值器

    /**
     * 通过给定的三个点计算贝塞尔曲线
     */
    class BezierEvaluator implements TypeEvaluator<PointF> {
        @Override
        public PointF evaluate(float fraction, PointF startValue,
                               PointF endValue) {
            final float t = fraction;
            float oneMinusT = 1.0f - t;
            PointF point = new PointF();

            //起始点p0
            PointF point0 = startValue;

            //中间点P1
            PointF point1 = new PointF();
            point1.set(mMid.x, mMid.y);

            //结束点P2
            PointF point2 = new PointF();
            point2.set(endValue.x, endValue.y);

            //计算X、Y坐标
            point.x = t * point2.x;
            point.y = oneMinusT * oneMinusT * (point0.y)
                    + 2 * t * oneMinusT * (point1.y)
                    + t * t * (point2.y);
//            Log.d("beisaer", "x=" + point.x + ";y=" + point.y);
            //动画结束时执行回调函数,并释放资源
            if(fraction==1f){
                mEndAnimationListener.onEndAnimationListener();
                bitmap=null;
                windowManager.removeView(mView);
            }
            return point;
        }
    }

其余部分可以根据需求进行变更。

代码地址: https://github.com/XDebuff/BesselCircle/

 

你可能感兴趣的:(Android实现抛物线小球)