前一階段由于項(xiàng)目需要實(shí)現(xiàn)一個(gè)點(diǎn)贊效果虎忌,后來通過貝塞爾曲線實(shí)現(xiàn)了該效果。效果如下
我們這里使用的是三階貝塞爾曲線。
三階貝塞爾曲線代碼如下
import android.animation.TypeEvaluator;
import android.graphics.PointF;
public class BezierEvaluator implements TypeEvaluator<PointF> {
private PointF pointF1;
private PointF pointF2;
public BezierEvaluator(PointF pointF1, PointF pointF2) {
this.pointF1 = pointF1;
this.pointF2 = pointF2;
}
@Override
public PointF evaluate(float time, PointF startValue,
PointF endValue) {
float timeLeft = 1.0f - time;
PointF point = new PointF();//結(jié)果
point.x = timeLeft * timeLeft * timeLeft * (startValue.x)
+ 3 * timeLeft * timeLeft * time * (pointF1.x)
+ 3 * timeLeft * time * time * (pointF2.x)
+ time * time * time * (endValue.x);
point.y = timeLeft * timeLeft * timeLeft * (startValue.y)
+ 3 * timeLeft * timeLeft * time * (pointF1.y)
+ 3 * timeLeft * time * time * (pointF2.y)
+ time * time * time * (endValue.y);
return point;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
like = (ImageView) findViewById(R.id.like);
like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PointF pointP0 = new PointF();//p0
pointP0.x = like.getX();
pointP0.y = like.getY();
original = pointP0;
PointF pointP3 = new PointF();//p3
pointP3.x = pointP0.x - 250;
pointP3.y = pointP0.y - 300;
PointF pointP1 = new PointF();//p1
pointP1.x = pointP0.x - 50;
pointP1.y = pointP0.y - 300;
PointF pointP2 = new PointF();//p2
pointP2.x = pointP0.x - 200;
pointP2.y = pointP0.y - 300;
// 初始化一個(gè)貝塞爾計(jì)算器- - 傳入
BezierEvaluator evaluator = new BezierEvaluator(pointP1,
pointP2);
ValueAnimator animator = ValueAnimator.ofObject(evaluator, pointP0,
pointP3);
animator.addUpdateListener(new BezierListener(like));
animator.setTarget(like);
animator.setDuration(1500);
animator.start();
}
});
}
private class BezierListener implements ValueAnimator.AnimatorUpdateListener {
private ImageView target;
public BezierListener(ImageView target) {
this.target = target;
}
@Override
public void onAnimationUpdate(ValueAnimator animation) {
//更新值之后更新UI
PointF pointF = (PointF) animation.getAnimatedValue();
target.setX(pointF.x);
target.setY(pointF.y);
// 這里順便做一個(gè)alpha動(dòng)畫
target.setAlpha(1 - animation.getAnimatedFraction());
target.setScaleX(1 + animation.getAnimatedFraction());
target.setScaleY(1 + animation.getAnimatedFraction());
if (animation.getAnimatedFraction() == 1) {
target.setX(original.x);
target.setY(original.y);
target.setAlpha(1.0f);
target.setScaleX(1);
target.setScaleY(1);
}
}
}
這里擴(kuò)展效果很多宙址,各位看官可以自己打開腦洞去實(shí)現(xiàn)了。