想做一个控件按照曲线轨迹运动的动画所以就用到了贝塞尔曲线
不废话直接上代码
public class BezierEvaluator implements TypeEvaluator<PointF> {
@Override
public PointF evaluate(float fraction, PointF startValue, PointF endValue) {
final float t = fraction;
float T = 1.0f - t;
PointF point = new PointF();
// PointF point0 = (PointF)startValue;起始坐标可以通过调用时传入
PointF point0 = new PointF();
PointF point1 = new PointF();
PointF point2 = new PointF();
PointF point3 = new PointF();
point0.set(-100, 305);
point1.set(-350, 280);//点一控制曲线弧度
point2.set(-400, 230);//点二控制曲线弧度
point3.set(160, 203);
// PointF point3 = (PointF)endValue;结束坐标可以通过调用时传入
//贝塞尔公式
point.x = T * T * T * (point0.x) + 3 * T * T * t * (point1.x) + 3 * T * t * t * (point2.x) + t * t * t * (point3.x);
point.y = T * T * T * (point0.y) + 3 * T * T * t * (point1.y) + 3 * T * t * t * (point2.y) + t * t * t * (point3.y);
return point;
}
//调用上面的class例如在mainactivity中,可以用下面的方法
private void Curve(final FrameLayout layout, int timer) {
ValueAnimator valueAnimator;
valueAnimator = ValueAnimator.ofObject(new BezierEvaluator(), new PointF(0, 0), new PointF(100, 100));//传入初始坐标与结束坐标根据需求调整
valueAnimator.setDuration(timer);//动画持续时间
valueAnimator.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
PointF pointF = (PointF) animation.getAnimatedValue();
layout.setX(pointF.x);
layout.setY(pointF.y);
}
});
//动画监听
valueAnimator.addListener(new AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
}
@Override
public void onAnimationCancel(Animator animation) {
}
});
//开始动画
valueAnimator.start();
}
通过 Curve(layout(想要运动的控件), 1000(运动时间)); 我们就可以使用了