# 贝塞尔曲线的应用(二)

## 购物车添加商品实现轨迹动画

device-2018-05-17-135829.gif

## 1.确定view的位置坐标

image.png

getLocationInWindow是以B为原点的C的坐标

getLocationOnScreen是以A为原点的C的坐标

## 2.拿到关键点的坐标后我们需要提供关于坐标的估值器

float fraction：动画的完成程度，0~1

T startValue：动画开始值

T endValue： 动画结束值（这里而外补充一点，要想得到当前的动画值其实也很简单，只需要用（动画开始值+动画完成程度*动画结束值））

image.png

```public class PointEvaluate implements TypeEvaluator {
private PointF controllerValue;

public PointEvaluate(PointF controllerValue) {
this.controllerValue = controllerValue;
}

@Override
public PointF evaluate(float fraction, PointF startValue, PointF endValue) {
float x = (1 - fraction) * (1 - fraction) * startValue.x + 2 * (1 - fraction) * fraction * controllerValue.x + fraction * fraction * endValue.x;
float y = (1 - fraction) * (1 - fraction) * startValue.y + 2 * (1 - fraction) * fraction * controllerValue.y + fraction * fraction * endValue.y;
return new PointF(x, y);
}
}```

3.我们可以在点击添加按钮的时候new一个imageView，让他的动画是从无到有(sacle,alpha动画），最后在运动轨迹变化的回调时不断变化imagview的位置.

```public class ShopActivity extends AppCompatActivity {
private int[] addView = new int[2];
private int[] shopView = new int[2];
private int[] parentView = new int[2];
private RelativeLayout rlMain;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop);
ivCar = findViewById(R.id.ivCar);
rlMain = findViewById(R.id.rlMain);
ivRemove = findViewById(R.id.ivRemove);

@Override
public void onClick(View v) {
rlMain.getLocationInWindow(parentView);
ivCar.getLocationInWindow(shopView);

final PointF endF = new PointF(shopView[0] - parentView[0], shopView[1] - parentView[1]);
final PointF controllerF = new PointF(endF.x, startF.y);
final ImageView imageView = new ImageView(ShopActivity.this);
imageView.setImageResource(R.mipmap.ic_car);
imageView.setScaleX(0);
imageView.setScaleY(0);
imageView.setX(startF.x);
imageView.setY(startF.y);

ValueAnimator valueAnimator = ValueAnimator.ofObject(new PointEvaluate(controllerF), startF, endF);
@Override
public void onAnimationUpdate(ValueAnimator animation) {
PointF pointF = (PointF) animation.getAnimatedValue();
imageView.setX(pointF.x);
imageView.setY(pointF.y);
imageView.setScaleY(animation.getAnimatedFraction());
imageView.setScaleX(animation.getAnimatedFraction());
}
});
valueAnimator.setDuration(1000);
valueAnimator.setTarget(imageView);
valueAnimator.start();

}
});
}
}```