實現效果:
需要注意的點:
ValueAnimator
ValueAnimator,是針對值的,也就是說ValueAnimator不會對控件進行任何操作,而是控制值的變化,然後我們監聽這個值的變化過程,從而來控制控件的變化。什麼意思呢?例如我們使用屬性動畫來控制TextView的位移,我們在初始化ValueAnimator時,會設置一個初始值和結束的值,假如我用這兩個值來控制TextView在y軸上的位置,然後設置監聽器,監聽初始值變化到結束值的過程,在不斷變化過程中,通過調用TextView的layout方法來不斷更新TextView的位置,從而實現位移動畫。
我們可以大概總結使用ValueAnimator的兩個主要過程:
(1). 初始化ValueAnimator,並設置初始值和結束值,還有動畫的時間,然後start。
(2). 給ValueAnimator設置監聽器,通過getAnimatedValue()拿到變化值,然後我們更新控件的變化。
實現步驟
1.首先封裝一個Ball粒子對象
public class Ball {
public int color; //圖片像素點顏色值
public float x; //粒子圓心座標x
public float y; //粒子圓心座標y
public float r; //粒子半徑
public float vX;//粒子運動水平方向速度
public float vY;//粒子運動垂直方向速度
public float aX;//粒子運動水平方向加速度
public float aY;//粒子運動垂直方向加速度
}
2.自定義SplitView 繼承View
2.1粒子相關屬初始化和ValueAnimator初始化
private void init() {
mPaint = new Paint();
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.cat);
for (int i = 0; i < mBitmap.getWidth(); i++) {
for (int j = 0; j < mBitmap.getHeight(); j++) {
Ball ball = new Ball();
ball.color = mBitmap.getPixel(i,j);
ball.x = i * d + (d/2);
ball.y = j * d + (d/2);
ball.r = d/2;
//速度(-20,20)
ball.vX = (float) (Math.pow(-1, Math.ceil(Math.random() * 1000)) * 20 * Math.random());
ball.vY = rangInt(-15, 35);
//加速度
ball.aX = 0;
ball.aY = 0.98f;
mBalls.add(ball);
}
}
mAnimator = ValueAnimator.ofFloat(0,1);
mAnimator.setRepeatCount(-1);
mAnimator.setDuration(2000);
mAnimator.setInterpolator(new LinearInterpolator());
mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
updateBall();
invalidate();
}
});
}
2.2更新粒子的位置
private void updateBall() {
for (Ball ball:mBalls) {
ball.x += ball.vX;
ball.y += ball.vY;
ball.vX += ball.aX;
ball.vY += ball.aY;
}
}
2.3重寫onDraw()方法繪製粒子
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.translate(250,250);
for (Ball ball:mBalls) {
mPaint.setColor(ball.color);
canvas.drawCircle(ball.x, ball.y, ball.r, mPaint);
}
}
2.4重寫onTouchEvent()方法觸發觸發時間並執行動畫
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
//執行動畫
mAnimator.start();
}
return super.onTouchEvent(event);
}